<template>
  <div class="school-detail-container">
    <!-- 头部信息区域 -->
    <div class="school-header">
      <div class="header-backdrop" :style="{ backgroundImage: `url(${schoolData.cover})` }"></div>
      <div class="header-content">
        <div class="school-basic">
          <el-avatar :size="90" :src="schoolData.logo" class="school-logo">
              <el-icon><School /></el-icon>
            </el-avatar>
          <div class="school-title-area">
            <h1 class="school-name">{{ schoolData.name }}</h1>
            <div class="school-stats">
              <div class="stat-item">
                <el-icon><ShoppingCart /></el-icon>
                <span>{{ schoolData.productCount || 0 }}件商品</span>
              </div>
              <div class="stat-item">
                <el-icon><User /></el-icon>
                <span>{{ schoolData.memberCount || 0 }}位成员</span>
              </div>
              <div class="stat-item">
                <el-icon><Star /></el-icon>
                <span>{{ schoolData.favoriteCount || 0 }}人关注</span>
              </div>
            </div>
          </div>
        </div>
        
        <div class="action-buttons">
          <!-- 操作按钮已移除 -->
        </div>
      </div>
    </div>

    <!-- 快速操作 - 右上方 -->
    <div class="quick-actions-container">
      <el-card shadow="hover" class="quick-actions-card">
        <template #header>
          <div class="card-header">
            <h3>快速操作</h3>
          </div>
        </template>
        <div class="action-content">
          <div class="action-grid">
            <div class="action-item" @click="publishProduct">
              <el-icon><ShoppingCart /></el-icon>
              <span>发布商品</span>
            </div>
            <div class="action-item" @click="publishWanted">
              <el-icon><Search /></el-icon>
              <span>发布求购</span>
            </div>
            <div class="action-item" @click="openMapView">
              <el-icon><MapLocation /></el-icon>
              <span>查看地图</span>
            </div>
            <div class="action-item" @click="shareSchool">
              <el-icon><Share /></el-icon>
              <span>分享学校</span>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧：学校简介 -->
      <div class="intro-sidebar">
        <el-card shadow="hover" class="intro-card">
          <template #header>
            <div class="card-header">
              <h3>学校简介</h3>
            </div>
          </template>
            <div class="intro-content">
            <p v-if="schoolData.description && schoolData.description.length > 0">
              {{ typeof schoolData.description === 'string' ? schoolData.description : schoolData.description[0] }}
              </p>
            <p v-else>暂无学校简介信息</p>
            
            <div class="intro-address">
              <h4><el-icon><Location /></el-icon> 学校地址</h4>
              <p>{{ schoolData.address || '暂无地址信息' }}</p>
            </div>
            
            <div class="mini-map-container" ref="miniMapContainer">
              <!-- 小地图将在这里加载 -->
            </div>
            
            <div class="school-tags" v-if="schoolData.tags && schoolData.tags.length > 0">
              <h4>学校标签</h4>
              <div class="tags-list">
                <el-tag 
                  v-for="tag in schoolData.tags" 
                  :key="tag"
                  type="info"
                  effect="plain"
                  class="school-tag"
                >
                  {{ tag }}
                </el-tag>
              </div>
            </div>
          </div>
        </el-card>
        
        <!-- 学校数据统计 -->
        <el-card shadow="hover" class="stats-card">
          <div class="stats-content">
            <div class="stat-box">
              <div class="stat-value">{{ schoolData.productCount || 0 }}</div>
              <div class="stat-label">在售商品</div>
            </div>
            <div class="stat-box">
              <div class="stat-value">{{ schoolData.memberCount || 0 }}</div>
              <div class="stat-label">学校成员</div>
            </div>
            <div class="stat-box">
              <div class="stat-value">{{ schoolData.favoriteCount || 0 }}</div>
              <div class="stat-label">关注人数</div>
            </div>
          </div>
        </el-card>
      </div>
      
      <!-- 右侧：校园二手商品 -->
      <div class="products-main">
        <div class="controls-container">
        <div class="segmented-control">
          <div class="tab-buttons">
            <button 
              class="tab-button" 
              :class="{ active: activeTab === 'products' }" 
              @click="activeTab = 'products'"
            >
              在售商品
            </button>
            <button 
              class="tab-button" 
              :class="{ active: activeTab === 'wanted' }" 
              @click="activeTab = 'wanted'"
            >
              求购信息
            </button>
          </div>
        </div>

        <!-- 商品筛选栏 -->
        <div class="filter-bar">
            <div class="filter-options">
            <el-select v-model="category" placeholder="商品分类" clearable class="custom-select">
              <template #prefix>
                <el-icon class="select-icon"><Grid /></el-icon>
              </template>
                <el-option
                  v-for="item in categoryOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                class="custom-option"
                />
              </el-select>
              
              <el-select v-model="sortBy" placeholder="排序方式">
                <el-option label="最新发布" value="newest" />
                <el-option label="价格从低到高" value="price_asc" />
                <el-option label="价格从高到低" value="price_desc" />
                <el-option label="最受欢迎" value="popular" />
              </el-select>
            </div>
            </div>
          </div>
          
        <!-- 在售商品内容 -->
        <div v-if="activeTab === 'products'">
          <div v-if="loading" class="loading-container">
            <el-skeleton :rows="5" animated />
            <el-skeleton :rows="5" animated />
          </div>
          
          <!-- 调试信息区域 -->
          <div v-if="showDebugInfo" class="debug-info">
            <p>activeTab: {{ activeTab }}</p>
            <p>loading: {{ loading }}</p>
            <p>products数组长度: {{ products.length }}</p>
            <p>hasProducts计算值: {{ hasProducts }}</p>
            <p>条件判断结果: v-if="activeTab === 'products'" ({{ activeTab === 'products' }})</p>
            <p>条件判断结果: v-if="loading" ({{ loading }})</p>
            <p>条件判断结果: v-else-if="products.length === 0" ({{ products.length === 0 }})</p>
            <button @click="products.value = rawResponseData.value" class="debug-btn">直接使用原始数据</button>
            <button @click="getSchoolProducts()" class="debug-btn">重新获取商品</button>
          </div>
          
          <div v-if="!loading && products.length === 0" class="empty-results">
            <el-empty description="暂无商品" :image-size="200">
              <template #description>
                <p>该学校暂无二手商品</p>
                <p class="empty-suggestion">成为第一个发布商品的人吧！</p>
              </template>
              <el-button type="primary" @click="publishProduct">发布商品</el-button>
            </el-empty>
          </div>
          
          <div v-if="!loading && products.length > 0" :class="['products-grid', { 'list-view': viewMode === 'list' }]">
            <el-card 
              v-for="product in products" 
              :key="product.id" 
              :body-style="{ padding: '0' }"
              class="product-card"
              shadow="hover"
              @click="goToProductDetail(product.id)"
            >
              <div class="product-image-container">
                <!-- 直接支持mainImageUrl作为图片源 -->
                <el-image 
                  :src="(product.image && !product.image.startsWith('http')) ? 
                        '/images/product/' + product.image : 
                        ((product.mainImageUrl && !product.mainImageUrl.startsWith('http')) ? 
                        '/images/product/' + product.mainImageUrl : 
                        (product.image || product.mainImageUrl))" 
                  fit="cover" 
                  class="product-image" 
                />
                <div v-if="product.isHot" class="product-badge hot">热门</div>
                <div v-if="product.isNew" class="product-badge new">新品</div>
              </div>
              <div class="product-info">
                <h3 class="product-title">{{ product.name }}</h3>
                <div class="product-meta">
                  <!-- 直接支持sellerName作为卖家名称 -->
                  <span class="product-seller">{{ product.seller || product.sellerName || product.userName || '未知卖家' }}</span>
                  <span class="product-condition">{{ product.condition || '良好' }}</span>
                </div>
                <div class="product-footer">
                  <div class="product-price">¥{{ product.price }}</div>
                  <div class="product-actions">
                    <el-button size="small" circle @click.stop="toggleProductFavorite(product)">
                      <el-icon><Star /></el-icon>
                    </el-button>
                    <el-button size="small" circle @click.stop="contactSeller(product)">
                      <el-icon><Message /></el-icon>
                    </el-button>
                  </div>
                </div>
              </div>
            </el-card>
          </div>
          </div>
          
        <!-- 求购信息内容 -->
        <div v-else-if="activeTab === 'wanted'">
          <div v-if="loadingWanted" class="loading-container">
            <el-skeleton :rows="5" animated />
          </div>
          
          <div v-else-if="!loadingWanted && wantedItems.length === 0" class="empty-results">
            <el-empty description="暂无求购信息" :image-size="200">
                <template #description>
                <p>该学校暂无求购信息</p>
                <p class="empty-suggestion">发布一条求购信息，找到你想要的物品</p>
                </template>
              <el-button type="primary" @click="publishWanted">发布求购</el-button>
              </el-empty>
            </div>
            
          <div v-else class="wanted-grid">
            <!-- 修改开始：应用 ios-request-card 结构 -->
            <div 
              v-for="item in wantedItems" 
              :key="item.id || item.purchaseId || item.requestId || item._id || Date.now() + Math.random()"
              class="ios-request-card" 
              @click="goToWantedDetail(item.id || item.purchaseId || item.requestId)"
            >
              <div class="request-header">
                <div class="user-info">
                  <!-- 修改头像处理逻辑，确保正确显示用户头像 -->
                  <el-avatar :size="40" 
                    :src="(item.user?.avatar && !item.user?.avatar.startsWith('http')) ? 
                          '/images/user/' + item.user?.avatar : 
                          (item.avatar && !item.avatar.startsWith('http')) ?
                          '/images/user/' + item.avatar :
                          (item.user?.avatar || item.avatar || defaultAvatar)">
                  </el-avatar>
                  <div class="user-details">
                    <div class="user-name">{{ item.user?.name || item.userName || item.publisherName || '匿名用户' }}</div>
                    <!-- 学校信息，如果求购信息本身没有学校，可以考虑从 schoolData 中获取 -->
                    <div class="user-school">{{ item.user?.school || schoolData.name }}</div>
                    </div>
                  </div>
                <div class="request-actions-top">
                  <div class="request-time">{{ formatTimeAgo(item.createTime || item.createdAt || item.publishTime) }}</div>
                  <!-- 收藏功能待实现，暂时只显示图标 -->
                  <el-button 
                      type="text" 
                      class="favorite-button" 
                      @click.stop="toggleWantedFavorite(item)"
                      :class="{ 'is-favorite': item.isFavorite }"
                  >
                      <el-icon><Star /></el-icon>
                  </el-button>
                  </div>
                </div>
              <div class="request-body">
                <h3 class="request-title">{{ item.title || item.name || item.itemName || '未命名求购' }}</h3>
                <p class="request-content">{{ 截断字符串((item.description || item.content || item.detail || '暂无描述'), 100) }}</p>
                <div class="request-tags">
                  <el-tag size="small" v-if="item.categoryName || item.category">{{ item.categoryName || item.category }}</el-tag>
                  <el-tag size="small" type="info" v-if="item.condition">{{ item.condition }}</el-tag>
                </div>
                    </div>
              <div class="request-footer">
                <div class="request-budget">预算: ¥{{ item.expectedPrice || item.price || item.targetPrice || item.budget || 0 }}</div>
                <div class="request-actions">
                  <!-- 联系用户功能，复用 contactSeller 或新建 contactRequester -->
                  <el-button type="primary" size="small" @click.stop="contactRequester(item)">联系</el-button>
                  <el-button plain size="small" @click.stop="shareWantedItem(item)">分享</el-button>
            </div>
              </div>
            </div>
            <!-- 修改结束 -->
          </div>
        
        <div class="pagination-container">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[12, 24, 36, 48]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="activeTab === 'products' ? totalProducts : totalWanted"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
    </div>
      </div>
    </div>

    <!-- 地图查看对话框 -->
    <el-dialog
      v-model="mapDialogVisible"
      title="学校位置"
      width="80%"
      :destroy-on-close="true"
    >
      <!-- <div class="full-map-container" ref="fullMapContainer"></div> -->
      <SchoolMapViewer 
        v-if="mapDialogVisible" 
        :initial-center="schoolData.location"
        style="height: 60vh; width: 100%;"
      />
    </el-dialog>

    <!-- 商品发布对话框 -->
    <el-dialog
      v-model="productDialogVisible"
      title="发布商品"
      width="60%"
      :destroy-on-close="true"
      class="apple-style-dialog"
    >
      <el-form ref="productFormRef" :model="productForm" :rules="productRules" label-width="120px" class="product-form">
        <!-- 新布局：上半部分左侧为主图上传，右侧为基本信息 -->
        <el-row :gutter="20" class="product-top-section">
          <!-- 左侧主图上传 -->
          <el-col :span="10">
            <el-form-item label="商品主图" prop="mainImage" class="main-image-uploader">
              <el-upload
                class="main-product-image"
                action="#"
                :auto-upload="false"
                :show-file-list="false"
                :on-change="handleMainImageChange"
                :before-upload="beforeUpload"
              >
                <img v-if="productForm.mainImage" :src="productForm.mainImage" class="main-image-preview" />
                <div v-else class="main-image-placeholder">
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传主图</div>
                </div>
              </el-upload>
              <div class="form-item-tips">建议尺寸: 800x800px，清晰展示商品正面</div>
            </el-form-item>
          </el-col>
          
          <!-- 右侧基本信息 -->
          <el-col :span="14">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="productForm.name" placeholder="请输入商品名称" class="apple-style-input half-width-input" />
            </el-form-item>

            <el-form-item label="商品分类" prop="category">
              <el-select v-model="productForm.category" placeholder="请选择商品分类" class="apple-style-select half-width-input">
                <el-option 
                  v-for="item in categoryOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>

            <el-form-item label="所属学校" prop="school">
              <el-select v-model="productForm.school" placeholder="请选择学校" class="apple-style-select half-width-input" disabled>
                <el-option :label="schoolData.name" :value="schoolData.id" />
              </el-select>
              <div class="form-item-tips">当前只能在本校发布商品</div>
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- 价格和成色信息 -->
        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="现价" prop="price">
              <el-input-number v-model="productForm.price" :min="0" :precision="2" :step="0.1" class="apple-style-input-number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="原价" prop="originalPrice">
              <el-input-number v-model="productForm.originalPrice" :min="0" :precision="2" :step="0.1" class="apple-style-input-number" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="成色" prop="condition">
              <el-select v-model="productForm.condition" placeholder="请选择成色" class="apple-style-select">
                <el-option label="全新" value="全新" />
                <el-option label="9成新" value="9成新" />
                <el-option label="8成新" value="8成新" />
                <el-option label="7成新" value="7成新" />
                <el-option label="6成新及以下" value="6成新及以下" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 商品描述和物品位置 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商品描述" prop="description" class="square-description">
              <el-input 
                v-model="productForm.description" 
                type="textarea" 
                rows="6"
                placeholder="请详细描述商品的成色、使用年限、配件等信息" 
                class="apple-style-textarea square-textarea" 
              />
            </el-form-item>
          </el-col>
          
          <el-col :span="12">
            <!-- 位置信息 - 简化为仅位置描述，移除地图 -->
            <el-form-item label="物品位置" prop="locationDescription">
              <div class="location-input-container">
                <el-input 
                  v-model="productForm.locationDescription" 
                  placeholder="请输入具体位置（学校名称将自动添加）" 
                  class="apple-style-input modern-input location-field"
                  @input="debounceGeocode"
                />
                <div class="location-status" v-if="productLocationStatus">
                  <el-tag :type="productLocationStatus.type" size="small" effect="light">
                    <template v-if="productLocationStatus.type === 'info'">
                      <i class="el-icon-loading" style="margin-right: 5px;"></i>
                      {{ productLocationStatus.message }}
                    </template>
                    <template v-else>
                      {{ productLocationStatus.message }}
                    </template>
                  </el-tag>
                </div>
              </div>
              <div class="form-item-tips">学校名称将自动添加到位置信息中，请直接输入具体位置如教学楼、宿舍等</div>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 底部附加图片上传 -->
        <el-form-item label="附加图片" class="additional-images">
          <el-upload v-model:file-list="fileList" action="#" list-type="picture-card"
            :auto-upload="false"
            :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :before-upload="beforeUpload"
            class="apple-style-upload">
            <el-icon>
              <Plus />
            </el-icon>
          </el-upload>
          <div class="form-item-tips">可上传多个角度的照片或细节图，最多8张</div>

          <el-dialog v-model="dialogVisible" class="preview-dialog">
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
          </el-dialog>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="apple-style-btn cancel-btn" @click="productDialogVisible = false">取消</el-button>
          <el-button class="apple-style-btn confirm-btn" type="primary" @click="handleSubmitProduct">发布</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 求购发布对话框 -->
    <el-dialog
      v-model="wantedDialogVisible"
      title="发布求购"
      width="40%"
      :destroy-on-close="true"
      class="apple-style-dialog"
    >
      <el-form :model="wantedForm" label-position="left" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="求购标题">
              <el-input v-model="wantedForm.title" placeholder="请输入求购标题" class="apple-style-input" style="width: 100%;" />
            </el-form-item>
          </el-col>
        </el-row>
        
        <!-- <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="所属学校">
              <el-select v-model="wantedForm.school" placeholder="请选择学校" class="apple-style-select" disabled style="width: 100%;">
                <el-option :label="schoolData.name" :value="schoolData.id" />
              </el-select>
              <div class="form-item-tips">当前只能在本校发布求购</div>
            </el-form-item>
          </el-col>
        </el-row> -->

        <el-form-item label="求购内容" prop="description">
          <el-input 
            v-model="wantedForm.description" 
            type="textarea" 
            rows="5"
            placeholder="详细描述您需要的物品、参数要求等" 
            class="apple-style-textarea"
          />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="求购分类">
              <el-select v-model="wantedForm.category" placeholder="选择分类" class="apple-style-select" style="width: 100%;">
                <el-option 
                  v-for="item in categoryOptions" 
                  :key="item.value" 
                  :label="item.label" 
                  :value="item.value" 
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
          
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="预算">
              <el-input-number v-model="wantedForm.budget" :min="0" :step="10" :precision="0" class="apple-style-input-number" style="width: 100%;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过期时间" prop="expireTime">
              <el-date-picker
                v-model="wantedForm.expireTime"
                type="datetime"
                placeholder="选择过期时间"
                style="width: 100%;"
                class="apple-style-select"
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="联系信息" prop="contactInfo">
          <el-input v-model="wantedForm.contactInfo" placeholder="请输入您的联系方式 (如QQ, 微信, 电话)" class="apple-style-input" style="width: 100%;" />
        </el-form-item>

        <!-- 位置信息 - 简化为只有输入框 -->
        <el-form-item label="交易位置">
          <div class="location-input-container">
            <el-input 
              v-model="wantedForm.locationDescription" 
              placeholder="请输入具体位置（学校名称将自动添加）" 
              class="apple-style-input modern-input location-field"
              @input="debounceWantedGeocode"
            />
            <div class="location-status" v-if="wantedLocationStatus">
              <el-tag :type="wantedLocationStatus.type" size="small" effect="light">
                <template v-if="wantedLocationStatus.type === 'info'">
                  <i class="el-icon-loading" style="margin-right: 5px;"></i>
                  {{ wantedLocationStatus.message }}
                </template>
                <template v-else>
                  {{ wantedLocationStatus.message }}
                </template>
              </el-tag>
            </div>
          </div>
          <div class="form-item-tips">学校名称已自动填充，请继续输入具体位置如教学楼、宿舍等</div>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="apple-style-btn cancel-btn" @click="wantedDialogVisible = false">取消</el-button>
          <el-button class="apple-style-btn confirm-btn" type="primary" @click="handleSubmitWanted">发布</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed, watch, onBeforeUnmount } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { 
  Search,
  List,
  Grid,
  Star,
  StarFilled,
  Share,
  Plus,
  Check,
  ShoppingCart,
  User,
  Message,
  School,
  Location,
  MapLocation,
  Money,
  Picture
} from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus';
import { createConversation } from '../../api/chat'
// 假设收藏/取消收藏求购的API在以下路径，如果路径不同请自行调整
import { favoriteRequest, unfavoriteRequest } from '../../api/request'; 
import SchoolMapViewer from '@/views/map/Map.vue'; // 确保地图组件已导入
import request from '@/utils/request'; // 确保正确导入请求工具

const route = useRoute();
const router = useRouter();
const miniMapContainer = ref(null);
const fullMapContainer = ref(null);
const mapDialogVisible = ref(false);
const productDialogVisible = ref(false);
const wantedDialogVisible = ref(false);
let miniMap = null;
let fullMap = null;
const defaultAvatar = ref('https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png'); // 默认头像

// 处理学校logo路径的函数
const getLogoUrl = (filename) => {
  if (!filename) return '';
  // 如果已经是完整的URL，则直接返回
  if (filename.startsWith('http')) return filename;
  
  try {
    // 尝试使用动态导入
    return new URL(`../../assets/images/${filename}`, import.meta.url).href;
  } catch (error) {
    console.error('加载logo图片失败:', error, filename);
    return '';
  }
};

// 状态变量
const loading = ref(false);
const loadingWanted = ref(false);
const activeTab = ref('products');
const schoolData = ref({
  id: '',
  name: '',
  logo: '',
  cover: '',
  description: [],
  address: '',
  location: [116.397428, 39.90923], // 默认位置
  tags: [],
  productCount: 0,
  memberCount: 0,
  favoriteCount: 0
});
const isJoined = ref(false);
const isFavorite = ref(false);
const searchKeyword = ref('');
const category = ref('');
const priceRange = ref('');
const sortBy = ref('newest');
const viewMode = ref('grid');
const currentPage = ref(1);
const pageSize = ref(24);
const totalProducts = ref(0);
const totalWanted = ref(0);
const products = ref([]);
const wantedItems = ref([]);



// 商品表单验证规则
const productRules = {
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择商品分类', trigger: 'change' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '价格必须大于 0', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
  ],
  condition: [
    { required: true, message: '请选择商品成色', trigger: 'change' }
  ],
  locationDescription: [
    { required: true, message: '请输入交易位置描述', trigger: 'blur' }
  ]
};

// 图片上传相关
const fileList = ref([]);
const dialogImageUrl = ref('');
const dialogVisible = ref(false);

const handleRemove = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const handlePictureCardPreview = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url;
  dialogVisible.value = true;
};

const beforeUpload = (file) => {
  const isImage = /^image\//.test(file.type);
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isImage) {
    ElMessage.error('只能上传图片文件!');
    return false;
  }
  if (!isLt2M) {
    ElMessage.error('图片大小不能超过 2MB!');
    return false;
  }
  return true;
};

// 发布求购相关
const wantedForm = ref({
  title: '',
  description: '', // 将 content 修改为 description
  category: '',
  budget: 0,
  schoolId: '',
  school: '',
  location: null,
  locationDescription: '',
  expireTime: null, 
  contactInfo: '' 
});

// 分类选项
const categoryOptions = [
  { label: '电子产品', value: 1 },
  { label: '手机数码', value: 2 },
  { label: '课本教材', value: 3 },
  { label: '宿舍用品', value: 4 },
  { label: '男装', value: 5 },
  { label: '球类装备', value: 6 },
  { label: '电脑配件', value: 7 },
  { label: '图书教材', value: 8 },
  { label: '考试资料', value: 9 },
  { label: '厨房用品', value: 10 },
  { label: '女装', value: 11 },
  { label: '健身器材', value: 12 },
  { label: '智能设备', value: 13 },
  { label: '小说文学', value: 14 },
  { label: '生活用品', value: 15 },
  { label: '服装鞋帽', value: 16 },
  { label: '运动健身', value: 17 },
  { label: '票券小物', value: 18 },
  { label: '其他', value: 99 }
];

// API基础URL
const API_BASE_URL = 'http://localhost:8080/api';

// 声明变量用于调试
const rawResponseData = ref(null);
const showDebugInfo = ref(false); // 设置为false，隐藏调试信息面板

// 监听状态变量，便于调试问题
watch(() => products.value, (newVal) => {
  console.log('products数组已更新:', newVal);
  console.log('商品数量:', newVal.length);
}, { deep: true });

// 检查空状态
const hasProducts = computed(() => {
  console.log('计算hasProducts:', products.value && products.value.length > 0);
  return products.value && products.value.length > 0;
});

// 表单引用
const productFormRef = ref(null);

// 地址转经纬度函数 - 使用高德地图地理编码API
const geocodeAddress = async (address, cityHint) => {
  if (!window.AMap) {
    console.error('高德地图API未加载');
    // 不返回默认值，而是抛出明确错误
    throw new Error('高德地图API未加载');
  }
  
  try {
    // 使用更长的超时时间
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('地址解析超时')), 10000); // 10秒超时
    });
    
    // 正常的地址解析Promise
    const geocodePromise = new Promise((resolve, reject) => {
      try {
        AMap.plugin(['AMap.Geocoder'], () => {
          // 检查是否成功加载地理编码插件
          if (!AMap.Geocoder) {
            console.error('高德地图地理编码插件加载失败');
            reject(new Error('地理编码插件加载失败'));
            return;
          }
          
          const geocoder = new AMap.Geocoder({
            city: cityHint || '全国', // 使用 cityHint，如果未提供则默认为 '全国'
            radius: 10000, // 默认搜索半径，单位米
            batch: false, // 不使用批量查询
            extensions: 'all', // 返回详细信息
          });
          
          // 首先尝试直接转换完整地址
          geocoder.getLocation(address, (status, result) => {
            console.log('地址解析返回状态:', status, '结果:', result, '城市限制:', cityHint || '全国');
            
            if (status === 'complete' && result.info === 'OK') {
              // 解析成功，返回第一个位置的经纬度
              if (result.geocodes && result.geocodes.length > 0) {
                const location = result.geocodes[0].location;
                console.log('地址解析成功:', address, '→', [location.lng, location.lat]);
                resolve([location.lng, location.lat]);
              } else {
                console.warn('地址解析成功但未找到结果:', address);
                // 尝试不同的组合方式解析（增加容错性）
                tryAlternativeAddress(address, geocoder, resolve, reject, cityHint);
              }
            } else {
              console.error('地址解析失败:', status, result);
              // 尝试不同的组合方式解析（增加容错性）
              tryAlternativeAddress(address, geocoder, resolve, reject, cityHint);
            }
          });
        });
      } catch (pluginError) {
        console.error('高德地图插件异常:', pluginError);
        reject(pluginError);
      }
    });
    
    // 使用Promise.race选择最先完成的Promise
    return await Promise.race([geocodePromise, timeoutPromise]);
  } catch (error) {
    console.error('地址解析出错:', error);
    throw error; // 向上传递错误，而不是静默返回默认值
  }
};

// 尝试不同的地址组合方式提高成功率
const tryAlternativeAddress = (address, geocoder, resolve, reject, cityHint) => {
  // 移除预定义地址数据库，完全使用高德地图API实时查询
  
  // 尝试添加省市信息后再查询 (如果cityHint没有提供或者不够具体)
  // 这部分逻辑可能需要根据cityHint的值来调整，如果cityHint已经是省市级别，则可能不需要这一步
  if (!address.includes('省') && !address.includes('市') && (!cityHint || !cityHint.includes('市'))) {
    const alternativeAddress = `${schoolData.value.province || ''} ${schoolData.value.city || ''} ${address}`.trim();
    console.log('尝试添加省市信息:', alternativeAddress);
    
    geocoder.getLocation(alternativeAddress, (status, result) => {
      if (status === 'complete' && result.info === 'OK' && result.geocodes && result.geocodes.length > 0) {
        const location = result.geocodes[0].location;
        console.log('添加省市后解析成功:', alternativeAddress, '→', [location.lng, location.lat]);
        resolve([location.lng, location.lat]);
      } else {
        // 尝试移除特定部分后再查询
        tryModifiedAddress(address, geocoder, resolve, reject, cityHint);
      }
    });
  } else {
    tryModifiedAddress(address, geocoder, resolve, reject, cityHint);
  }
};

// 尝试修改地址提高成功率
const tryModifiedAddress = (address, geocoder, resolve, reject, cityHint) => {
  // 提取可能的学校名称
  const schoolPattern = /(.*?大学|.*?学院|.*?学校)/;
  const matches = address.match(schoolPattern);
  
  if (matches && matches[1]) {
    const schoolName = matches[1];
    console.log('尝试仅使用学校名称:', schoolName);
    
    geocoder.getLocation(schoolName, (status, result) => {
      if (status === 'complete' && result.info === 'OK' && result.geocodes && result.geocodes.length > 0) {
        const location = result.geocodes[0].location;
        console.log('学校名称解析成功:', schoolName, '→', [location.lng, location.lat]);
        resolve([location.lng, location.lat]);
      } else {
        // 尝试更深层次的查询 - 移除校区信息
        const simplifiedAddress = address.replace(/[东南西北]?校区|分校|新校区|老校区|主校区/, '');
        if (simplifiedAddress !== address) {
          console.log('尝试移除校区信息:', simplifiedAddress);
          
          geocoder.getLocation(simplifiedAddress, (status, result) => {
            if (status === 'complete' && result.info === 'OK' && result.geocodes && result.geocodes.length > 0) {
              const location = result.geocodes[0].location;
              console.log('简化地址解析成功:', simplifiedAddress, '→', [location.lng, location.lat]);
              resolve([location.lng, location.lat]);
            } else {
              // 如果所有尝试都失败，尝试最后的查询
              tryFinalAttempt(address, geocoder, resolve, reject, cityHint);
            }
          });
        } else {
          // 如果无校区信息可移除，尝试最后的查询
          tryFinalAttempt(address, geocoder, resolve, reject, cityHint);
        }
      }
    });
  } else {
    // 如果无法提取学校名称，尝试最后的查询
    tryFinalAttempt(address, geocoder, resolve, reject, cityHint);
  }
};

// 最后的查询尝试 - 使用POI搜索
const tryFinalAttempt = (address, geocoder, resolve, reject, cityHint) => {
  // 尝试使用POI搜索
  try {
    AMap.plugin(['AMap.PlaceSearch'], () => {
      // 检查是否成功加载POI搜索插件
      if (!AMap.PlaceSearch) {
        console.error('高德地图POI搜索插件加载失败');
        reject(new Error('POI搜索插件加载失败'));
        return;
      }
      
      // 创建POI搜索实例
      console.log('开始POI搜索:', address, '城市限制:', cityHint || '全国');
      const placeSearch = new AMap.PlaceSearch({
        city: cityHint || '全国', // 使用 cityHint，如果未提供则默认为 '全国'
        citylimit: !!cityHint, // 如果提供了cityHint，则限制在城市内
        pageSize: 1, // 仅返回第一个结果
        pageIndex: 1,
        extensions: 'all', // 返回详细信息
        type: '科教文化服务;高等院校', // 优先搜索高校
        autoFitView: false // 不自动调整地图视野
      });
      
      // 执行搜索请求
      placeSearch.search(address, (status, result) => {
        console.log('POI搜索返回:', status, result);
        
        if (status === 'complete' && result.info === 'OK' && result.poiList && result.poiList.pois && result.poiList.pois.length > 0) {
          const poi = result.poiList.pois[0];
          const location = poi.location;
          console.log('POI搜索成功:', address, '→', [location.lng, location.lat], '地点名称:', poi.name);
          resolve([location.lng, location.lat]);
        } else {
          // 尝试不指定类型进行更广泛的搜索
          console.log('特定类型POI搜索失败，尝试通用搜索');
          const generalPlaceSearch = new AMap.PlaceSearch({
            city: cityHint || '全国', // 使用 cityHint
            citylimit: !!cityHint, // 如果提供了cityHint，则限制
            pageSize: 1,
            pageIndex: 1
          });
          
          generalPlaceSearch.search(address, (genStatus, genResult) => {
            console.log('通用POI搜索返回:', genStatus, genResult);
            
            if (genStatus === 'complete' && genResult.info === 'OK' && genResult.poiList && genResult.poiList.pois && genResult.poiList.pois.length > 0) {
              const genPoi = genResult.poiList.pois[0];
              const genLocation = genPoi.location;
              console.log('通用POI搜索成功:', address, '→', [genLocation.lng, genLocation.lat], '地点名称:', genPoi.name);
              resolve([genLocation.lng, genLocation.lat]);
            } else {
              console.warn('所有地址解析方法都失败:', address);
              reject(new Error('无法通过任何方法解析该地址'));
            }
          });
        }
      });
    });
  } catch (error) {
    console.error('POI搜索过程异常:', error);
    reject(error);
  }
};

// 获取校内商品
const getSchoolProducts = async () => {
  console.log('开始获取校内商品数据...');
  loading.value = true;
  products.value = []; // 重置products数组，避免旧数据干扰
  totalProducts.value = 0; // 重置总数
  
  try {
    const schoolId = route.params.id;
      const apiUrl = `${API_BASE_URL}/schools/${schoolId}/products?page=${currentPage.value}&pageSize=${pageSize.value}`;
      
      console.log('请求商品数据:', apiUrl);
      
      const response = await fetch(apiUrl);
      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }
      
      const responseData = await response.json();
      rawResponseData.value = responseData; // 保存原始响应，用于调试
      console.log('原始响应数据:', responseData);
      
      let rawProducts = [];
      let total = 0;
    
      if (responseData) {
        if (Array.isArray(responseData)) {
          rawProducts = responseData;
          total = responseData.length;
        }
        else if (responseData.code === 200 && responseData.data) {
          if (Array.isArray(responseData.data)) {
            rawProducts = responseData.data;
            total = responseData.data.length;
          } 
        else if (responseData.data && (Array.isArray(responseData.data.items) || Array.isArray(responseData.data.content)) ) {
          rawProducts = responseData.data.items || responseData.data.content;
          total = responseData.data.totalElements || responseData.data.total || rawProducts.length;
          }
          else if (responseData.data && typeof responseData.data === 'object') {
            for (const key in responseData.data) {
              if (Array.isArray(responseData.data[key])) {
                rawProducts = responseData.data[key];
                total = rawProducts.length;
                break;
              }
            }
          }
        }
        else if (responseData.items && Array.isArray(responseData.items)) {
          rawProducts = responseData.items;
          total = responseData.total || rawProducts.length;
      } else if (responseData.content && Array.isArray(responseData.content)) { // 兼容Spring Pageable的content
        rawProducts = responseData.content;
        total = responseData.totalElements || rawProducts.length;
        }
        else if (typeof responseData === 'object') {
          for (const key in responseData) {
            if (Array.isArray(responseData[key])) {
              rawProducts = responseData[key];
              total = rawProducts.length;
              break;
            } 
          else if (responseData[key] && typeof responseData[key] === 'object' && (Array.isArray(responseData[key].items) || Array.isArray(responseData[key].content)) ) {
            rawProducts = responseData[key].items || responseData[key].content;
            total = responseData[key].totalElements || responseData[key].total || rawProducts.length;
              break;
            }
          }
          if (rawProducts.length === 0 && responseData.id) {
            rawProducts = [responseData];
            total = 1;
          }
        }
      }
      
      if (rawProducts && rawProducts.length > 0) {
        let mappedProducts = rawProducts.map(product => {
        if (!product) return null;
        return {
            id: product.id || 0,
            name: product.name || product.productName || product.title || '未命名商品',
            image: product.image || product.mainImageUrl || product.coverImage || product.imageUrl || 'https://placeholder.pics/svg/300/DEDEDE/555555/商品图片',
            price: typeof product.price === 'number' ? product.price : (parseFloat(product.price) || 0),
            seller: product.seller || product.sellerName || product.userName || '未知卖家',
          sellerId: product.sellerId, // 确保 sellerId 被映射
            condition: product.condition || (product.conditionLevel ? `${product.conditionLevel}成新` : '良好'),
            isHot: product.isHot || product.hot || false,
            isNew: product.isNew || product.new || false,
            description: product.description || product.desc || '',
            category: product.category || product.categoryName || '',
            categoryId: product.categoryId || 0
          };
      }).filter(product => product !== null);
        
        let filteredProducts = [...mappedProducts];
        if (category.value) {
          // 使用分类ID进行筛选
          const categoryId = Number(category.value);
          filteredProducts = filteredProducts.filter(product => 
            product.categoryId === categoryId || 
            Number(product.category) === categoryId
          );
        }
        if (priceRange && priceRange.value) {
          const range = priceRange.value.split('-');
          if (range.length === 2) {
            const minPrice = Number(range[0]);
            const maxPrice = Number(range[1]);
          filteredProducts = filteredProducts.filter(product => product.price >= minPrice && product.price <= maxPrice);
          } else if (priceRange.value.endsWith('+')) {
            const minPrice = Number(priceRange.value.replace('+', ''));
          filteredProducts = filteredProducts.filter(product => product.price >= minPrice);
          }
        }
        products.value = filteredProducts; 
      totalProducts.value = total;
      } else {
      console.warn('后端返回的商品数据为空或格式不符合预期');
        products.value = [];
        totalProducts.value = 0;
    }
  } catch (error) {
    console.error('获取校内商品失败:', error);
    ElMessage.error(`获取校内商品失败: ${error.message || '请检查网络连接'}`);
    products.value = [];
    totalProducts.value = 0;
  } finally {
    loading.value = false;
  }
};

// 获取求购信息
const getWantedItems = async () => {
  console.log('getWantedItems CALLED. Current wantedItems length:', wantedItems.value.length, 'Current totalWanted:', totalWanted.value, 'CurrentPage:', currentPage.value);
  loadingWanted.value = true;
  // 仅在请求第一页数据时才清空现有列表
  if (currentPage.value === 1) {
    console.log('Resetting wantedItems for page 1');
    wantedItems.value = []; 
    totalWanted.value = 0;
  }

  try {
    const schoolId = route.params.id;
    // 使用 currentPage 和 pageSize 作为求购列表的分页参数
      const apiUrl = `${API_BASE_URL}/schools/${schoolId}/wanted?page=${currentPage.value}&pageSize=${pageSize.value}`;
    console.log('请求求购数据 URL:', apiUrl);
      
      const response = await fetch(apiUrl);
    console.log('求购 API 响应状态:', response.status);

      if (!response.ok) {
      // 如果请求失败，也应该显示错误而不是一直转圈
      const errorText = await response.text();
      console.error('求购 API 请求失败:', response.status, errorText);
      throw new Error(`API请求失败: ${response.status} - ${errorText}`);
      }
      
    const responseData = await response.json();
    console.log('求购 API 原始响应 JSON:', JSON.parse(JSON.stringify(responseData)));
      
    // 检查API响应码和数据结构
    if (responseData && responseData.code === 200 && responseData.data && Array.isArray(responseData.data.content)) {
      console.log('求购数据有效，API返回 content 长度:', responseData.data.content.length);
      const newItems = responseData.data.content;
      
      if (newItems.length > 0) {
        // 如果是第一页，直接赋值；否则追加
        wantedItems.value = currentPage.value === 1 ? newItems : [...wantedItems.value, ...newItems];
      } else if (currentPage.value === 1) {
        // 第一页就没有数据
        wantedItems.value = [];
      }
      // 如果 newItems 为空且不是第一页，则 wantedItems.value 保持不变 (表示没有更多数据)
      
      totalWanted.value = responseData.data.totalElements || 0; // 使用后端返回的总数
      console.log('更新后 wantedItems (length):', wantedItems.value.length, 'Data:', wantedItems.value);
      console.log('更新后 totalWanted:', totalWanted.value);

    } else {
      // API响应码不是200，或者数据结构不符合预期
      console.warn('后端返回的求购数据格式不符合预期或无数据:', responseData);
      if (currentPage.value === 1) { // 如果是第一页获取就失败/无数据
        wantedItems.value = [];
        totalWanted.value = 0;
      }
      // 可以选择性地抛出错误或显示提示
      // ElMessage.error('获取求购数据格式错误');
    }
  } catch (error) {
    console.error('获取校内求购信息执行过程中出错:', error);
    ElMessage.error(`获取求购信息失败: ${error.message || '未知网络错误'}`);
    // 发生错误时，如果是第一页，则清空列表
    if (currentPage.value === 1) {
        wantedItems.value = [];
        totalWanted.value = 0;
    }
  } finally {
    loadingWanted.value = false;
    console.log('getWantedItems FINISHED. loadingWanted:', loadingWanted.value, 'Final wantedItems (length):', wantedItems.value.length, 'Final totalWanted:', totalWanted.value);
  }
};

// 初始化小地图
const initMiniMap = () => {
  if (!miniMapContainer.value) return;
  
  // 注意：实际项目中需要加载高德地图或其他地图API
  if (window.AMap) {
    try {
      miniMap = new window.AMap.Map(miniMapContainer.value, {
        zoom: 15,
        center: schoolData.value.location,
        resizeEnable: true,
        zoomEnable: false,
        dragEnable: false,
        controlsEnable: false
      });
      
      // 添加标记
      new window.AMap.Marker({
        position: schoolData.value.location,
        map: miniMap
      });
    } catch (error) {
      console.error('初始化小地图失败:', error);
    }
  }
};

// 初始化完整地图
const initFullMap = () => {
  if (!fullMapContainer.value) return;
  
  // 注意：实际项目中需要加载高德地图或其他地图API
  if (window.AMap) {
    try {
      fullMap = new window.AMap.Map(fullMapContainer.value, {
        zoom: 15,
        center: schoolData.value.location,
        resizeEnable: true,
      });
      
      // 添加标记
      new window.AMap.Marker({
        position: schoolData.value.location,
        map: fullMap
      });
    } catch (error) {
      console.error('初始化完整地图失败:', error);
    }
  }
};

// 打开地图查看对话框
const openMapView = () => {
  // 确保 schoolData.location 是一个有效的经纬度数组
  if (schoolData.value && schoolData.value.location && 
      Array.isArray(schoolData.value.location) && 
      schoolData.value.location.length === 2 && 
      typeof schoolData.value.location[0] === 'number' && 
      typeof schoolData.value.location[1] === 'number') {
  mapDialogVisible.value = true;
  } else {
    ElMessage.warning('学校位置信息无效，无法打开地图。');
    console.error('无效的学校位置数据:', schoolData.value.location);
    // 可以选择尝试重新获取学校数据或提示用户
  }
};

// 加入学校
const joinSchool = async () => {
  try {
    ElMessage.info('正在处理加入学校请求...');
    
    // 调用API加入学校
    const response = await fetch(`${API_BASE_URL}/schools/${schoolData.value.id}/join`, { 
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `请求失败 (${response.status})`);
    }
    
    ElMessage.success('已成功加入学校');
  isJoined.value = true;
    schoolData.value.memberCount++;
  } catch (error) {
    console.error('加入学校失败:', error);
    ElMessage.error(`加入学校失败: ${error.message || '未知错误'}`);
  }
};

// 退出学校
const leaveSchool = async () => {
  try {
    const result = await ElMessageBox.confirm(
      '确定要退出该学校吗？',
      '退出确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    );
    
    if (result === 'confirm') {
      ElMessage.info('正在处理退出学校请求...');
      
      // 调用API退出学校
      const response = await fetch(`${API_BASE_URL}/schools/${schoolData.value.id}/leave`, { 
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        }
      });
      
      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        throw new Error(errorData.message || `请求失败 (${response.status})`);
      }
      
      ElMessage.success('已退出学校');
  isJoined.value = false;
      schoolData.value.memberCount--;
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('退出学校失败:', error);
      ElMessage.error(`退出学校失败: ${error.message || '未知错误'}`);
    }
  }
};

// 关注/取消关注学校
const toggleFavorite = async () => {
  try {
    const action = isFavorite.value ? 'unfavorite' : 'favorite';
    ElMessage.info(`正在${isFavorite.value ? '取消关注' : '关注'}学校...`);
    
    // 调用API关注/取消关注学校
    const response = await fetch(`${API_BASE_URL}/schools/${schoolData.value.id}/${action}`, { 
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    });
    
    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.message || `请求失败 (${response.status})`);
    }
    
    if (isFavorite.value) {
      // 取消关注
      ElMessage.success('已取消关注学校');
      isFavorite.value = false;
      schoolData.value.favoriteCount--;
    } else {
      // 关注学校
      ElMessage.success('已关注学校');
      isFavorite.value = true;
      schoolData.value.favoriteCount++;
    }
  } catch (error) {
    console.error('操作失败:', error);
    ElMessage.error(`操作失败: ${error.message || '未知错误'}`);
  }
};


// 搜索商品
const searchProducts = () => {
  currentPage.value = 1;
  getSchoolProducts();
};

// 联系卖家
const contactSeller = async (product) => {
  // 阻止事件冒泡
  event.stopPropagation();
  
  try {
    // 检查用户登录状态
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
    const userId = userInfo.id

    if (!userId) {
      ElMessage.error('请先登录才能联系卖家')
      return
    }

    if (!product || !product.sellerId) {
      ElMessage.error('无法获取卖家信息')
      return
    }

    // 创建会话
    const response = await createConversation({
      userId: userId,
      partnerId: product.sellerId
    })

    // 根据后端返回的错误码来判断
    if (!response) {
      ElMessage.error('网络异常，请稍后重试')
      return
    }
    
    // 只有当code为200时才视为成功
    if (response.code !== 200) {
      // 根据不同错误码显示不同错误信息
      switch (response.code) {
        case 400:
          ElMessage.error(response.message || '请求参数错误')
          break
        case 401:
          ElMessage.error('用户未登录或登录已过期')
          break
        case 403:
          ElMessage.error('您没有权限联系该卖家')
          break
        case 404:
          ElMessage.error('卖家信息不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误，请稍后重试')
          break
        default:
          // 始终优先使用后端返回的错误信息
          ElMessage.error(response.message || `创建会话失败(${response.code})`)
      }
      // 无论什么错误都不跳转
      return
    }

    // 只有成功时才显示提示并跳转
  ElMessage.success(`已打开与 ${product.seller} 的聊天窗口`);
    router.push({
      path: '/chat',
      query: {
        sellerId: product.sellerId,
        productId: product.id
      }
    });
  } catch (error) {
    console.error('联系卖家出错:', error)
    ElMessage.error('联系卖家失败，请稍后重试')
  }
};

// 处理标签切换
watch(activeTab, (newValue) => {
  if (newValue === 'products') {
    getSchoolProducts();
  } else if (newValue === 'wanted') {
    getWantedItems();
  }
});

// 修改翻页处理，根据当前标签加载不同数据
const handleCurrentChange = (val) => {
  currentPage.value = val;
  if (activeTab.value === 'products') {
    getSchoolProducts();
  } else {
    getWantedItems();
  }
};

// 页面大小变化
const handleSizeChange = (val) => {
  pageSize.value = val;
  if (activeTab.value === 'products') {
    getSchoolProducts();
  } else {
    getWantedItems();
  }
};

// 查看商品详情
const goToProductDetail = (productId) => {
  router.push(`/product/${productId}`);
};

// 收藏商品
const toggleProductFavorite = (product) => {
  // 阻止事件冒泡
  event.stopPropagation();
  
  ElMessage.success(`${product.isFavorite ? '已取消收藏' : '已收藏'} ${product.name}`);
  product.isFavorite = !product.isFavorite;
};

// 生命周期钩子
onMounted(() => {
  getSchoolDetail();
  getSchoolProducts();
  getWantedItems();
  checkUserStatus();
});

// 检查用户是否已加入/关注该学校
const checkUserStatus = async () => {
  try {
    const schoolId = route.params.id;
    const userId = localStorage.getItem('userId') || '';
    
    if (!userId) {
        console.warn('用户未登录，无法获取用户与学校关系状态');
        isJoined.value = false;
        isFavorite.value = false;
        return;
    }

      console.log('检查用户与学校关系状态:', `${API_BASE_URL}/schools/${schoolId}/user-status?userId=${userId}`);
      const response = await fetch(`${API_BASE_URL}/schools/${schoolId}/user-status?userId=${userId}`);
      
      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }
      
      const data = await response.json();
      
      if (data && typeof data.isJoined === 'boolean' && typeof data.isFavorite === 'boolean') {
        isJoined.value = data.isJoined;
        isFavorite.value = data.isFavorite;
        console.log('成功从后端获取用户状态:', data);
      } else {
        console.warn('后端返回的用户状态数据格式不符合预期:', data);
      isJoined.value = false; // API返回格式不对时，默认为false
      isFavorite.value = false;
    }
  } catch (error) {
    console.error('检查用户状态失败:', error);
    ElMessage.error(`检查用户状态失败: ${error.message || '请检查网络连接'}`);
    isJoined.value = false; // 出错时默认为false
    isFavorite.value = false;
  }
};



// 在文件最后删除地图相关变量和函数
const mapContainer = ref(null);
const wantedMapContainer = ref(null);
let productMap = null;
let wantedMap = null;

// 初始化商品发布地图
const initProductMap = () => {
  if (!mapContainer.value) return;
  
  // 如果已经加载过高德地图
  if (window.AMap) {
    try {
      productMap = new window.AMap.Map(mapContainer.value, {
        zoom: 15,
        center: productForm.value.location || schoolData.value.location,
        resizeEnable: true
      });
      
      // 添加标记
      const marker = new window.AMap.Marker({
        position: productForm.value.location || schoolData.value.location,
        draggable: true, // 可拖动
        map: productMap
      });
      
      // 拖动结束后更新位置
      marker.on('dragend', (e) => {
        productForm.value.location = [e.lnglat.lng, e.lnglat.lat];
        console.log('商品位置已更新为:', productForm.value.location);
      });
      
      // 点击地图更新位置
      productMap.on('click', (e) => {
        marker.setPosition([e.lnglat.lng, e.lnglat.lat]);
        productForm.value.location = [e.lnglat.lng, e.lnglat.lat];
        console.log('商品位置已更新为:', productForm.value.location);
      });
    } catch (error) {
      console.error('初始化商品地图失败:', error);
    }
  }
};

// 初始化求购发布地图
const initWantedMap = () => {
  if (!wantedMapContainer.value) return;
  
  // 如果已经加载过高德地图
  if (window.AMap) {
    try {
      wantedMap = new window.AMap.Map(wantedMapContainer.value, {
        zoom: 15,
        center: wantedForm.value.location || schoolData.value.location,
        resizeEnable: true
      });
      
      // 添加标记
      const marker = new window.AMap.Marker({
        position: wantedForm.value.location || schoolData.value.location,
        draggable: true, // 可拖动
        map: wantedMap
      });
      
      // 拖动结束后更新位置
      marker.on('dragend', (e) => {
        wantedForm.value.location = [e.lnglat.lng, e.lnglat.lat];
        console.log('求购位置已更新为:', wantedForm.value.location);
      });
      
      // 点击地图更新位置
      wantedMap.on('click', (e) => {
        marker.setPosition([e.lnglat.lng, e.lnglat.lat]);
        wantedForm.value.location = [e.lnglat.lng, e.lnglat.lat];
        console.log('求购位置已更新为:', wantedForm.value.location);
      });
    } catch (error) {
      console.error('初始化求购地图失败:', error);
    }
  }
};

// 位置状态显示
const productLocationStatus = ref(null);
const wantedLocationStatus = ref(null);

// 防抖定时器
let geocodeTimer = null;
let wantedGeocodeTimer = null;

// 商品位置防抖处理
const debounceGeocode = (value) => {
  // 清除之前的定时器
  if (geocodeTimer) clearTimeout(geocodeTimer);
  
  // 如果输入框为空，清除状态
  if (!value) {
    productLocationStatus.value = null;
    return;
  }
  
  // 显示正在查询状态
  productLocationStatus.value = { type: 'info', message: '正在查询位置...' };
  
  // 添加一个安全超时，确保无论如何状态会更新
  const safetyTimeout = setTimeout(() => {
    if (productLocationStatus.value && productLocationStatus.value.type === 'info') {
      productLocationStatus.value = { type: 'warning', message: '位置查询超时，请重试或手动输入详细地址' };
    }
  }, 12000); // 12秒比geocodeAddress的10秒超时稍长
  
  // 设置新的定时器，延迟800ms执行，避免频繁API调用
  geocodeTimer = setTimeout(async () => {
    try {
      // 组合完整地址
      const fullAddress = `${schoolData.value.name} ${value}`;
      console.log('开始地址解析:', fullAddress, '使用城市提示:', schoolData.value.city);
      
      // 调用地理编码API，并传入城市提示
      const coordinates = await geocodeAddress(fullAddress, schoolData.value.city);
      
      // 清除安全超时
      clearTimeout(safetyTimeout);
      
      if (coordinates && Array.isArray(coordinates) && coordinates.length === 2) {
        // 转换成功，保存经纬度并更新状态
        productForm.value.location = coordinates;
        productLocationStatus.value = { 
          type: 'success', 
          message: `位置已确认: ${coordinates[0].toFixed(4)}, ${coordinates[1].toFixed(4)}` 
        };
        console.log('地址解析成功并更新UI:', coordinates);
      } else {
        // 转换返回值异常
        productLocationStatus.value = { type: 'warning', message: '位置格式异常，请输入更详细的地址' };
        console.error('地址解析返回值异常:', coordinates);
      }
    } catch (error) {
      // 清除安全超时
      clearTimeout(safetyTimeout);
      
      console.error('地址解析出错:', error.message || error);
      
      // 显示具体的错误信息
      if (error.message && error.message.includes('超时')) {
        productLocationStatus.value = { type: 'error', message: '查询超时，请检查网络连接或使用更详细的地址' };
      } else if (error.message && error.message.includes('API未加载')) {
        productLocationStatus.value = { type: 'error', message: '地图服务未加载，请刷新页面重试' };
      } else {
        productLocationStatus.value = { type: 'error', message: `位置查询失败: ${error.message || '未知错误'}` };
      }
    }
  }, 800);
};

// 求购位置防抖处理
const debounceWantedGeocode = (value) => {
  // 清除之前的定时器
  if (wantedGeocodeTimer) clearTimeout(wantedGeocodeTimer);
  
  // 如果输入框为空，清除状态
  if (!value) {
    wantedLocationStatus.value = null;
    return;
  }
  
  // 显示正在查询状态
  wantedLocationStatus.value = { type: 'info', message: '正在查询位置...' };
  
  // 添加一个安全超时，确保无论如何状态会更新
  const safetyTimeout = setTimeout(() => {
    if (wantedLocationStatus.value && wantedLocationStatus.value.type === 'info') {
      wantedLocationStatus.value = { type: 'warning', message: '位置查询超时，请重试或手动输入详细地址' };
    }
  }, 12000); // 12秒比geocodeAddress的10秒超时稍长
  
  // 设置新的定时器，延迟800ms执行，避免频繁API调用
  wantedGeocodeTimer = setTimeout(async () => {
    try {
      // 组合完整地址
      const fullAddress = `${schoolData.value.name} ${value}`;
      console.log('开始地址解析 (求购):', fullAddress, '使用城市提示:', schoolData.value.city);
      
      // 调用地理编码API，并传入城市提示
      const coordinates = await geocodeAddress(fullAddress, schoolData.value.city);
      
      // 清除安全超时
      clearTimeout(safetyTimeout);
      
      if (coordinates && Array.isArray(coordinates) && coordinates.length === 2) {
        // 转换成功，保存经纬度并更新状态
        wantedForm.value.location = coordinates;
        wantedLocationStatus.value = { 
          type: 'success', 
          message: `位置已确认: ${coordinates[0].toFixed(4)}, ${coordinates[1].toFixed(4)}` 
        };
        console.log('地址解析成功并更新UI (求购):', coordinates);
      } else {
        // 转换返回值异常
        wantedLocationStatus.value = { type: 'warning', message: '位置格式异常，请输入更详细的地址' };
        console.error('地址解析返回值异常 (求购):', coordinates);
      }
    } catch (error) {
      // 清除安全超时
      clearTimeout(safetyTimeout);
      
      console.error('地址解析出错 (求购):', error.message || error);
      
      // 显示具体的错误信息
      if (error.message && error.message.includes('超时')) {
        wantedLocationStatus.value = { type: 'error', message: '查询超时，请检查网络连接或使用更详细的地址' };
      } else if (error.message && error.message.includes('API未加载')) {
        wantedLocationStatus.value = { type: 'error', message: '地图服务未加载，请刷新页面重试' };
      } else {
        wantedLocationStatus.value = { type: 'error', message: `位置查询失败: ${error.message || '未知错误'}` };
      }
    }
  }, 800);
};

// 在表单提交前转换地址为经纬度
const handleSubmitProduct = async () => {
  if (!productFormRef.value) return;

  try {
    // 表单验证
    const valid = await productFormRef.value.validate()
      .then(valid => valid)
      .catch(error => {
        console.error('表单验证失败:', error);
        return false;
      });
    
    if (!valid) {
      ElMessage.warning('请完善表单信息');
      return;
    }

    // 显示加载中
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在发布商品...',
      background: 'rgba(255, 255, 255, 0.7)'
    });

    // 创建FormData对象用于提交表单和文件
    const formData = new FormData();
    
    // 添加商品基本信息
    formData.append('name', productForm.value.name);
    formData.append('categoryId', String(productForm.value.category)); // 确保传递分类ID
    formData.append('price', String(productForm.value.price));
    formData.append('description', productForm.value.description);
    formData.append('condition', productForm.value.condition);
    
    // 添加学校ID
    formData.append('schoolId', productForm.value.school);
    
    // 如果没有位置信息，添加基于学校的位置
    if (productForm.value.location) {
      if (Array.isArray(productForm.value.location)) {
        formData.append('longitude', String(productForm.value.location[0]));
        formData.append('latitude', String(productForm.value.location[1]));
      }
    }
    
    // 添加位置描述 - 组合学校名称和用户输入的位置
    const schoolName = schoolData.value.name || '';
    const userLocation = productForm.value.locationDescription || '';
    
    // 如果用户输入了位置，则组合学校名称和用户位置
    if (userLocation) {
      // 检查用户输入的位置是否已经包含学校名称，避免重复
      const finalLocation = userLocation.includes(schoolName) 
        ? userLocation 
        : `${schoolName} ${userLocation}`;
      formData.append('locationDescription', finalLocation);
    } else {
      // 如果用户没有输入位置，至少提交学校名称
      formData.append('locationDescription', schoolName);
    }
    
    // 使用Set存储文件以避免重复
    const uniqueFiles = new Set();
    
    // 添加主图文件（如果有）
    if (productForm.value.mainImageFile) {
      uniqueFiles.add(productForm.value.mainImageFile);
      console.log('添加主图文件:', productForm.value.mainImageFile.name);
    }
    
    // 添加附加图片文件
    const additionalFiles = fileList.value
      .filter(file => file.raw)
      .map(file => file.raw);
    
    if (additionalFiles.length > 0) {
      console.log(`处理${additionalFiles.length}个附加图片文件`);
      additionalFiles.forEach(file => {
        if (file) {
          uniqueFiles.add(file);
          console.log('处理附加图片:', file.name);
        }
      });
    }
    
    // 添加所有唯一的文件到FormData
    uniqueFiles.forEach(file => {
      formData.append('files', file);
      console.log('最终添加到formData的图片:', file.name);
    });
    
    // 检查是否添加了至少一张图片
    if (uniqueFiles.size === 0) {
      ElMessage.warning('请至少上传一张商品图片');
      loadingInstance.close();
      return;
    }
    
    console.log('准备发送请求，共有图片:', uniqueFiles.size, '张');
    
    // 调用发布商品API
    try {
      // 确保使用正确的API路径
      const url = `${API_BASE_URL}/products`;
      console.log('发送请求到:', url);
      
      const response = await fetch(url, {
        method: 'POST',
        body: formData,
        headers: {
          // 不要设置Content-Type，让浏览器自动设置multipart/form-data边界
          'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
        }
      });
      
      const responseData = await response.json();
      console.log('请求响应:', responseData);
      
      // 关闭加载中
      loadingInstance.close();
      
      if (response.ok && responseData.code === 200) {
        ElMessage.success('商品发布成功');
        productDialogVisible.value = false;
        
        // 重置表单
        productFormRef.value.resetFields();
        productLocationStatus.value = null;
        fileList.value = [];
        productForm.value.mainImageFile = null;
        
        // 刷新商品列表
        if (activeTab.value === 'products') {
          getSchoolProducts();
        }
      } else {
        const errorMsg = responseData?.message || '发布失败，请重试';
        console.error('发布失败:', errorMsg, responseData);
        ElMessage.error(errorMsg);
      }
    } catch (requestError) {
      console.error('发送请求失败:', requestError);
      loadingInstance.close();
      ElMessage.error('网络请求失败: ' + (requestError.message || '未知错误'));
    }
  } catch (error) {
    console.error('发布商品过程出错:', error);
    ElMessage.error('发布失败: ' + (error.message || '请重试'));
  }
};

// 求购发布也添加地址转换
const handleSubmitWanted = async () => {
  try {
    // 处理预算值，确保它是一个正数
    if (typeof wantedForm.value.budget !== 'number' || isNaN(wantedForm.value.budget) || wantedForm.value.budget < 0) {
      wantedForm.value.budget = 0; // 设置默认值为0
    }
    
    // 验证表单 - 使用数组存储错误信息，一次性显示所有错误
    const errors = [];
    
    if (!wantedForm.value.title || wantedForm.value.title.trim() === '') {
      errors.push('请输入求购标题');
    }
    
    if (!wantedForm.value.description || wantedForm.value.description.trim() === '') { // 修改 content 为 description
      errors.push('请输入求购内容');
    }
    
    if (!wantedForm.value.category) {
      errors.push('请选择求购分类');
    }
    
    if (!wantedForm.value.expireTime) {
      errors.push('请选择过期时间');
    }

    if (!wantedForm.value.contactInfo || wantedForm.value.contactInfo.trim() === '') {
      errors.push('请输入联系信息');
    }
    
    // 如果有错误，显示错误消息并返回
    if (errors.length > 0) {
      ElMessage.warning(errors.join('；'));
      return;
    }
    
    // 显示加载中
    const loadingInstance = ElLoading.service({
      lock: true,
      text: '正在发布求购信息...',
      background: 'rgba(255, 255, 255, 0.7)'
    });
    
    // 如果没有位置信息，添加基于学校的位置
    if (!wantedForm.value.location && wantedForm.value.locationDescription) {
      wantedLocationStatus.value = { type: 'info', message: '使用学校位置作为默认位置' };
      wantedForm.value.location = schoolData.value.name;
    }
    
    // 准备请求参数
    const requestData = {
      title: wantedForm.value.title.trim(),
      description: wantedForm.value.description.trim(), // 修改 content 为 description
      categoryId: wantedForm.value.category, 
      budget: wantedForm.value.budget, 
      schoolId: wantedForm.value.school,
      locationDescription: wantedForm.value.locationDescription ?         (wantedForm.value.locationDescription.includes(schoolData.value.name) ?          wantedForm.value.locationDescription.trim() :          `${schoolData.value.name} ${wantedForm.value.locationDescription}`.trim()) :        schoolData.value.name.trim(),
      expireTime: wantedForm.value.expireTime, // 添加 expireTime
      contactInfo: wantedForm.value.contactInfo.trim() // 添加 contactInfo
    };
    
    // 如果有经纬度位置信息，添加到请求中
    if (wantedForm.value.location && Array.isArray(wantedForm.value.location)) {
      requestData.longitude = wantedForm.value.location[0];
      requestData.latitude = wantedForm.value.location[1];
    }
    
    console.log('发布求购:', requestData);
    
    // 调用发布求购API
    const url = `${API_BASE_URL}/requests`;
    const response = await fetch(url, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': localStorage.getItem('token') ? `Bearer ${localStorage.getItem('token')}` : ''
      },
      body: JSON.stringify(requestData)
    });
    
    // 获取响应数据
    let responseData;
    try {
      responseData = await response.json();
    } catch (e) {
      console.error('解析响应JSON出错:', e);
      responseData = { code: 500, message: '服务器响应格式错误' };
    }
    
    // 关闭加载指示器
    loadingInstance.close();
    
    if (response.ok && responseData.code === 200) {
      ElMessage.success('求购信息发布成功');
      wantedDialogVisible.value = false;
      
      // 重置表单
      wantedForm.value = {
        title: '',
        description: '', // 修改 content 为 description
        category: '',
        budget: 0,
        schoolId: '',
        school: '',
        location: null,
        locationDescription: '',
        expireTime: null, // 重置
        contactInfo: '' // 重置
      };
      wantedLocationStatus.value = null;
      
      // 刷新求购列表
      if (activeTab.value === 'wanted') {
        getWantedItems();
      }
    } else {
      // 处理错误响应
      let errorMsg = responseData?.message || '发布失败，请重试';
      
      // 尝试解析ValidationError 格式的错误消息
      if (responseData.errors && typeof responseData.errors === 'object') {
        const errorMessages = [];
        for (const field in responseData.errors) {
          if (responseData.errors[field]) {
            errorMessages.push(responseData.errors[field]);
          }
        }
        if (errorMessages.length > 0) {
          errorMsg = errorMessages.join('；');
        }
      }
      
      console.error('发布失败:', errorMsg, responseData);
      ElMessage.error(errorMsg);
    }
  } catch (error) {
    console.error('发布求购过程出错:', error);
    ElMessage.error('发布失败，请重试: ' + (error.message || '网络错误'));
  }
};

// 发布商品
const publishProduct = () => {
  // 设置学校ID和学校名称
  productForm.value.schoolId = schoolData.value.id;
  productForm.value.school = schoolData.value.id;
  // 设置默认位置（不再使用地图坐标，而是使用学校名称作为默认位置标识）
  productForm.value.location = schoolData.value.name;
  // 预填充学校名称作为位置描述前缀 - 改为初始化为空字符串
  productForm.value.locationDescription = ''; 
  // 重置图片相关字段
  productForm.value.mainImage = '';
  productForm.value.mainImageFile = null;
  fileList.value = [];
  // 重置位置状态
  productLocationStatus.value = null;
  
  // 打开商品发布对话框
  productDialogVisible.value = true;
};

// 联系求购人
const contactBuyer = (item) => {
  ElMessage.success(`已打开与${item.userName}的聊天窗口`);
};

// 发布求购信息
const publishWanted = () => {
  // 设置学校ID和学校名称
  wantedForm.value.schoolId = schoolData.value.id;
  wantedForm.value.school = schoolData.value.id;
  // 设置默认位置（不再使用地图坐标，而是使用学校名称作为默认位置标识）
  wantedForm.value.location = schoolData.value.name;
  // 预填充学校名称作为位置描述前缀 - 改为初始化为空字符串
  wantedForm.value.locationDescription = ''; 
  // 重置位置状态
  wantedLocationStatus.value = null;
  
  // 打开求购发布对话框
  wantedDialogVisible.value = true;
};

// 获取学校详情
const getSchoolDetail = async () => {
  loading.value = true;
  try {
    const schoolId = route.params.id;
    
    // 尝试从后端获取学校详情
      console.log('请求学校详情:', `${API_BASE_URL}/schools/${schoolId}`);
      const response = await fetch(`${API_BASE_URL}/schools/${schoolId}`);
      
      if (!response.ok) {
        throw new Error(`API请求失败: ${response.status}`);
      }
      
      const responseData = await response.json();
      
      // 验证数据有效性 - 检查是否有code字段（标准API响应）
      if (responseData.code === 200 && responseData.data) {
      // 先保存必要的信息，特别是地址
      schoolData.value.id = responseData.data.id;
      schoolData.value.name = responseData.data.name;
      schoolData.value.logo = responseData.data.logo ? getLogoUrl(responseData.data.logo) : '';
      schoolData.value.cover = responseData.data.cover;
      schoolData.value.description = responseData.data.description;
      schoolData.value.address = responseData.data.address; // 获取地址
      schoolData.value.city = responseData.data.city; // 获取城市
      schoolData.value.province = responseData.data.province; // 获取省份
      schoolData.value.tags = responseData.data.tags;
      schoolData.value.productCount = responseData.data.productCount;
      schoolData.value.memberCount = responseData.data.memberCount;
      schoolData.value.favoriteCount = responseData.data.favoriteCount;
      // 其他需要从 responseData.data 赋值的字段也应在此处处理

        console.log('成功从后端获取学校详情:', schoolData.value.name);
      
      if (schoolData.value.address) {
        try {
          console.log(`尝试对地址 "${schoolData.value.address}" 进行地理编码`);
          const coordinates = await geocodeAddress(schoolData.value.address);
          if (coordinates && Array.isArray(coordinates) && coordinates.length === 2 &&
              typeof coordinates[0] === 'number' && typeof coordinates[1] === 'number') {
            schoolData.value.location = coordinates;
            console.log('地理编码成功, 位置更新为:', schoolData.value.location);
          } else {
            console.warn('地理编码未能返回有效坐标，将使用 schoolData 中预设的默认位置。');
            // schoolData.value.location 已有默认值，无需再次赋值
          }
        } catch (geoError) {
          console.error('地理编码失败:', geoError, '将使用 schoolData 中预设的默认位置。');
          // schoolData.value.location 已有默认值，无需再次赋值
        }
      } else {
        console.warn('学校地址为空，无法进行地理编码，将使用 schoolData 中预设的默认位置。');
        // schoolData.value.location 已有默认值，无需再次赋值
      }
        
        // 加载小地图
        nextTick(() => {
          initMiniMap();
        });
      } 
      // 也处理直接返回学校对象的情况
      else if (responseData.id) {
      // 与上方逻辑类似，先保存地址，然后尝试地理编码
      schoolData.value.id = responseData.id;
      schoolData.value.name = responseData.name;
      schoolData.value.logo = responseData.logo ? getLogoUrl(responseData.logo) : '';
      schoolData.value.cover = responseData.cover;
      schoolData.value.description = responseData.description;
      schoolData.value.address = responseData.address; // 获取地址
      schoolData.value.city = responseData.city; // 获取城市
      schoolData.value.province = responseData.province; // 获取省份
      schoolData.value.tags = responseData.tags;
      schoolData.value.productCount = responseData.productCount;
      schoolData.value.memberCount = responseData.memberCount;
      schoolData.value.favoriteCount = responseData.favoriteCount;

        console.log('成功从后端获取学校详情(直接格式):', responseData.name);

      if (schoolData.value.address) {
        try {
          console.log(`尝试对地址 "${schoolData.value.address}" 进行地理编码 (直接格式)`);
          const coordinates = await geocodeAddress(schoolData.value.address);
          if (coordinates && Array.isArray(coordinates) && coordinates.length === 2 &&
              typeof coordinates[0] === 'number' && typeof coordinates[1] === 'number') {
            schoolData.value.location = coordinates;
            console.log('地理编码成功 (直接格式), 位置更新为:', schoolData.value.location);
          } else {
            console.warn('地理编码未能返回有效坐标 (直接格式)，将使用 schoolData 中预设的默认位置。');
          }
        } catch (geoError) {
          console.error('地理编码失败 (直接格式):', geoError, '将使用 schoolData 中预设的默认位置。');
        }
      } else {
        console.warn('学校地址为空 (直接格式)，无法进行地理编码，将使用 schoolData 中预设的默认位置。');
      }
        
        // 加载小地图
        nextTick(() => {
          initMiniMap();
        });
      } 
      else {
        console.warn('后端返回的学校详情数据格式不符合预期:', responseData);
      throw new Error('学校详情数据格式错误');
      }
  } catch (error) {
    console.error('获取学校详情失败:', error);
    ElMessage.error(`获取学校详情失败: ${error.message || '请检查网络连接'}`);
    // 保持默认的错误状态 schoolData 结构
    schoolData.value = { 
        id: '', name: '获取失败', logo: '', cover: '', description: ['无法加载学校详情。'],
        address: '', location: [116.397428, 39.90923], // 保留默认位置
        tags: [], productCount: 0,
        memberCount: 0, favoriteCount: 0
    };
    // 即使获取详情失败，也尝试使用默认位置初始化地图
    nextTick(() => {
        initMiniMap();
    });
  } finally {
    loading.value = false;
  }
};

// 添加到productForm ref对象中表示主图
const productForm = ref({
  name: '',
  category: '',
  price: 0,
  originalPrice: 0,
  description: '',
  images: [],
  mainImage: '', // 添加主图字段
  mainImageFile: null, // 存储主图文件对象
  schoolId: '',
  school: '',
  condition: '',
  location: null,
  locationDescription: ''
});

// 添加 handleMainImageSuccess 函数处理主图上传
const handleMainImageSuccess = (res, file) => {
  // 根据实际API返回格式处理
  if (res.code === 200 && res.data) {
    // 如果API返回了图片URL
    productForm.value.mainImage = res.data.url || res.data;
  } else if (res.url) {
    // 如果API直接返回了url
    productForm.value.mainImage = res.url;
  } else {
    // 如果API没有返回URL，可以使用本地预览URL
    productForm.value.mainImage = URL.createObjectURL(file.raw);
  }
  
  ElMessage.success('主图上传成功');
};

const 截断字符串 = (str, len) => {
  if (!str) return '';
  return str.length > len ? str.substring(0, len) + '...' : str;
};

const formatTimeAgo = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  const now = new Date();
  const seconds = Math.round((now.getTime() - date.getTime()) / 1000);
  const minutes = Math.round(seconds / 60);
  const hours = Math.round(minutes / 60);
  const days = Math.round(hours / 24);
  const weeks = Math.round(days / 7);
  const months = Math.round(days / 30.44); // 平均每月天数
  const years = Math.round(days / 365.25); // 平均每年天数

  if (isNaN(seconds) || seconds < 0) return '刚刚'; // 处理无效日期或未来日期

  if (seconds < 60) return `${seconds}秒前`;
  if (minutes < 60) return `${minutes}分钟前`;
  if (hours < 24) return `${hours}小时前`;
  if (days < 7) return `${days}天前`;
  if (weeks < 5) return `${weeks}周前`; 
  if (months < 12) return `${months}月前`;
  return `${years}年前`;
  // 更详细的日期可以考虑: 
  // if (days > 30) { 
  //   return date.toLocaleDateString('zh-CN', { year: 'numeric', month: 'long', day: 'numeric' }); 
  // }
};

// 在 <script setup> 中添加 goToWantedDetail, toggleWantedFavorite, contactRequester, shareWantedItem 的桩函数
const goToWantedDetail = (id) => {
  // router.push(`/requests/${id}`); // 假设求购详情页路由为 /requests/:id
  if (id) {
    router.push(`/requests/${id}`); 
  } else {
    console.warn('goToWantedDetail: id is undefined');
    ElMessage.warning('无法跳转到详情，缺少ID');
  }
};

const toggleWantedFavorite = async (item) => {
  // 假设 userStore 或 localStorage 中有登录状态和用户信息
  const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
  const token = localStorage.getItem('token');

  if (!token || !userInfo.id) {
    ElMessage.warning('请先登录再操作');
    router.push({ path: '/login', query: { redirect: route.fullPath } });
    return;
  }

  // 添加一个加载状态，防止重复点击 (如果item对象是深度响应式的)
  if (item.isFavoriting) return;
  item.isFavoriting = true;

  try {
    if (item.isFavorite) {
      const response = await unfavoriteRequest(item.id); // API需要求购项的ID
      if (response && response.code === 200) {
        item.isFavorite = false;
        ElMessage.success('已取消收藏');
      } else {
        ElMessage.error(response?.message || '取消收藏失败');
      }
    } else {
      const response = await favoriteRequest(item.id); // API需要求购项的ID
      if (response && response.code === 200) {
        item.isFavorite = true;
        ElMessage.success('已收藏');
      } else {
        ElMessage.error(response?.message || '收藏失败');
      }
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试');
    console.error('Favorite operation failed for wanted item:', error);
  } finally {
    item.isFavoriting = false;
  }
};

const contactRequester = async (item) => {
  try {
    // 检查用户是否已登录
    const token = localStorage.getItem('token');
    const userInfo = localStorage.getItem('userInfo');
    if (!token || !userInfo) {
        ElMessage.warning('请先登录后再联系求购者');
        router.push('/login?redirect=' + encodeURIComponent(router.currentRoute.value.fullPath));
        return;
    }
    
    const userId = JSON.parse(userInfo).id;
    if (!userId) {
        ElMessage.warning('无法获取用户信息，请重新登录');
        return;
    }

    // 获取求购发布者的ID
    const requesterId = item.userId || item.user?.id || item.publisherId;
    if (!requesterId) {
        ElMessage.error('无法获取求购者信息');
        return;
    }
    
    if (userId === requesterId) {
        ElMessage.info('您不能和自己聊天哦');
        return;
    }
    
    // 发送联系请求
    const response = await fetch(`${API_BASE_URL}/requests/${item.id}/contact`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Authorization': `Bearer ${token}`
        },
        body: JSON.stringify({
            message: '您好，我看到了您的求购信息，想和您详细聊一下。'
        })
    });
    
    // 获取响应数据
    const data = await response.json();
    console.log('联系求购者响应:', data);
    
    // 根据后端返回的错误码来判断
    if (!data) {
        ElMessage.error('网络异常，请稍后重试');
        return;
    }
    
    // 只有当code为200时才视为成功
    if (data.code !== 200) {
        // 根据不同错误码显示不同错误信息
        switch (data.code) {
            case 400:
                ElMessage.error(data.message || '请求参数错误');
                break;
            case 401:
                ElMessage.error('用户未登录或登录已过期');
                break;
            case 403:
                ElMessage.error('您没有权限联系该求购者');
                break;
            case 404:
                ElMessage.error('求购信息不存在');
                break;
            case 409:
                ElMessage.error(data.message || '不能联系自己');
                break;
            case 500:
                ElMessage.error('服务器内部错误，请稍后重试');
                break;
            default:
                // 始终优先使用后端返回的错误信息
                ElMessage.error(data.message || `联系失败(${data.code})`);
        }
        // 无论什么错误都不跳转
        return;
    }
    
    // 联系成功，显示成功消息
    ElMessage.success(data.message || '已成功发起联系');
    
    // 从后端响应中获取会话相关信息
    const responseData = data.data || {};
    
    // 跳转到聊天页面，使用后端返回的会话ID或对话相关信息
    if (responseData.conversationId || responseData.chatId) {
        router.push({
            path: '/chat',
            query: {
                conversationId: responseData.conversationId || responseData.chatId,
                // 后端可能还会返回其他有用的参数，也一并传递
                sellerId: responseData.sellerId || requesterId,
                requestId: item.id
            }
        });
    } else {
        // 如果后端没有返回会话ID，则使用用户ID跳转
        router.push({
            path: '/chat',
            query: {
                partnerId: requesterId,
                requestId: item.id
            }
        });
    }
  } catch (error) {
    console.error('联系求购人出错:', error);
    ElMessage.error('联系求购人失败，请稍后重试');
  }
};

const shareWantedItem = (item) => {
  console.log('Share wanted item:', item);
  // 实现分享逻辑，例如复制链接
  const shareUrl = `${window.location.origin}/requests/${item.id}`; // 假设的求购详情页链接
  navigator.clipboard.writeText(shareUrl).then(() => {
    ElMessage.success('求购链接已复制到剪贴板');
  }).catch(err => {
    ElMessage.error('复制失败');
    console.error('Could not copy text: ', err);
  });
};

// 添加 handleMainImageChange 函数处理主图选择
const handleMainImageChange = (file) => {
  if (file.raw) {
    // 创建本地预览URL
    productForm.value.mainImage = URL.createObjectURL(file.raw);
    // 保存文件对象以便后续提交
    productForm.value.mainImageFile = file.raw;
  }
};

</script>

<style scoped>
.school-detail-container {
  width: 100%;
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 12px;
  font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', 'SF Pro Display', 'Helvetica Neue', Arial, sans-serif;
  color: #1d1d1f;
  letter-spacing: -0.01em;
  position: relative;
}

@media (max-width: 1440px) {
  .school-detail-container {
    max-width: 100%;
}
}

/* 头部样式 */
.school-header {
  position: relative;
  height: 280px;
  border-radius: 16px;
  overflow: hidden;
  margin-bottom: 32px;
  box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
  width: calc(100% - 300px);
}

.header-backdrop {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-size: cover;
  background-position: center;
  filter: none;
  opacity: 0.9;
}

.header-backdrop::after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, rgba(0, 0, 0, 0.2), rgba(0, 0, 0, 0.5));
}

.header-content {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 100%;
  padding: 0 36px;
  color: white;
  z-index: 1;
}

.school-basic {
  display: flex;
  align-items: center;
}

.school-logo {
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.15);
  border: 2px solid rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
}

.school-title-area {
  margin-left: 24px;
}

.school-name {
  margin: 0 0 12px 0;
  font-size: 32px;
  font-weight: 600;
  letter-spacing: -0.02em;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
}

.school-stats {
  display: flex;
  gap: 20px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 15px;
  font-weight: 500;
}

.action-buttons {
  display: flex;
  gap: 12px;
}

.action-btn {
  transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  background-color: rgba(255, 255, 255, 0.15);
  color: white;
  padding: 10px 20px;
  border-radius: 18px;
  font-weight: 500;
  font-size: 14px;
}

.action-btn:hover {
  transform: translateY(-2px);
  background-color: rgba(255, 255, 255, 0.25);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.2);
}

.action-btn:active {
  transform: translateY(0);
  background-color: rgba(255, 255, 255, 0.2);
}

/* 主要内容区域样式 */
.main-content {
  display: flex;
  gap: 24px;
  margin-bottom: 40px;
}

/* 侧边栏样式 */
.intro-sidebar {
  width: 280px;
  flex-shrink: 0;
  display: flex;
  flex-direction: column;
}

.intro-card {
  border-radius: 20px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  border: none;
  overflow: hidden;
  background-color: #fff;
  transition: transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), box-shadow 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  height: auto;
  margin-bottom: 20px;
}

.intro-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 16px 8px 16px;
  border-bottom: none;
}

.card-header h3 {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  letter-spacing: -0.02em;
  color: #1d1d1f;
}

.intro-content {
  font-size: 15px;
  line-height: 1.6;
  color: #424245;
  padding: 0 16px 16px 16px;
}

.intro-address {
  margin-top: 16px;
  background-color: #f5f5f7;
  padding: 12px;
  border-radius: 14px;
}

.intro-address h4 {
  font-size: 15px;
  font-weight: 600;
  margin: 0 0 6px 0;
  display: flex;
  align-items: center;
  gap: 6px;
  color: #1d1d1f;
}

.intro-address p {
  margin: 0;
  color: #424245;
}

.mini-map-container {
  height: 150px;
  margin: 16px 0;
  border-radius: 14px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.school-tags {
  margin-top: 16px;
}

.school-tags h4 {
  font-size: 15px;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #1d1d1f;
}

.tags-list {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.school-tag {
  font-size: 12px;
  font-weight: 500;
  border-radius: 12px;
  padding: 4px 10px;
  background-color: #f5f5f7;
  color: #424245;
  border: none;
}

/* 商品区域样式 */
.products-main {
  flex: 1;
  min-width: 0; /* 防止flex子项溢出 */
}

.controls-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.segmented-control {
  margin-bottom: 0;
}

.tab-buttons {
  display: flex;
  background-color: #f5f5f7;
  border-radius: 12px;
  padding: 4px;
  width: fit-content;
}

.tab-button {
  padding: 8px 20px;
  border-radius: 10px;
  border: none;
  background: transparent;
  font-size: 14px;
  font-weight: 500;
  color: #424245;
  cursor: pointer;
  transition: all 0.2s ease;
}

.tab-button.active {
  background-color: #ffffff;
  color: #1d1d1f;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.08);
}

.tab-button:hover:not(.active) {
  background-color: rgba(255, 255, 255, 0.5);
}

.filter-bar {
  display: flex;
  justify-content: flex-end;
  background-color: transparent;
  padding: 0;
  border-radius: 0;
  box-shadow: none;
  margin-bottom: 0;
}

.filter-options {
  display: flex;
  gap: 16px;
}

.custom-select {
  width: 160px;
}

.filter-options .el-select {
  height: 38px;
}

.filter-options :deep(.el-input__wrapper) {
  padding: 0 10px;
  height: 38px;
  border-radius: 8px;
}

.select-icon {
  margin-right: 8px;
  color: #0071e3;
}

.custom-select :deep(.el-input__wrapper) {
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  padding: 0 14px;
  height: 44px;
  transition: all 0.2s ease;
}

.custom-select :deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(0, 113, 227, 0.2), 0 2px 12px rgba(0, 0, 0, 0.1);
}

.custom-select :deep(.el-input__suffix) {
  color: #0071e3;
}

.custom-select :deep(.el-select-dropdown__item) {
  padding: 10px 14px;
  font-size: 14px;
  border-radius: 8px;
  margin: 2px 4px;
}

.custom-select :deep(.el-select-dropdown__item.hover), 
.custom-select :deep(.el-select-dropdown__item:hover) {
  background-color: rgba(0, 113, 227, 0.1);
}

.custom-select :deep(.el-select-dropdown__item.selected) {
  background-color: rgba(0, 113, 227, 0.15);
  color: #0071e3;
  font-weight: 600;
}

.custom-select :deep(.el-select__tags) {
  margin-top: 1px;
}

.view-mode :deep(.el-button) {
  border-radius: 12px;
  height: 36px;
}

.loading-container,
.empty-results {
  padding: 60px 0;
  text-align: center;
}

.empty-suggestion {
  margin-top: 8px;
  color: #86868b;
  font-size: 15px;
}

.products-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 20px;
}

.products-grid.list-view {
  grid-template-columns: 1fr;
}

.product-card {
  border-radius: 16px;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.08);
  border: none;
  transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  cursor: pointer;
  overflow: hidden;
}

.product-card:hover {
  transform: translateY(-6px) scale(1.02);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.12);
}

.product-image-container {
  position: relative;
  height: 200px;
}

.list-view .product-image-container {
  height: 140px;
  width: 140px;
  float: left;
}

.product-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.product-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 4px 12px;
  font-size: 12px;
  font-weight: 500;
  color: white;
  border-radius: 12px;
  letter-spacing: -0.01em;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.2);
  backdrop-filter: blur(4px);
  -webkit-backdrop-filter: blur(4px);
}

.product-badge.hot {
  background-color: rgba(245, 108, 108, 0.9);
}

.product-badge.new {
  background-color: rgba(103, 194, 58, 0.9);
}

.product-info {
  padding: 18px;
}

.list-view .product-info {
  margin-left: 140px;
  padding: 18px;
}

.product-title {
  margin: 0 0 10px 0;
  font-size: 17px;
  font-weight: 600;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  color: #1d1d1f;
  letter-spacing: -0.01em;
}

.product-meta {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #86868b;
  margin-bottom: 10px;
}

.product-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.product-price {
  font-size: 20px;
  font-weight: 600;
  color: #1d1d1f;
}

.product-actions {
  display: flex;
  gap: 8px;
}

.product-actions :deep(.el-button) {
  box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.1);
  --el-button-hover-border-color: transparent;
  --el-button-active-border-color: transparent;
}

.product-actions :deep(.el-button:hover) {
  box-shadow: 0 0 0 2px #0071e3;
  background-color: rgba(0, 113, 227, 0.05);
}

.pagination-container {
  margin-top: 32px;
  display: flex;
  justify-content: center;
}

.pagination-container :deep(.el-pagination .el-pagination__jump) {
  font-size: 14px;
}

.pagination-container :deep(.el-pagination button) {
  border-radius: 50%;
  min-width: 32px;
}

.pagination-container :deep(.el-pagination .el-pager li) {
  border-radius: 50%;
  font-size: 14px;
  min-width: 32px;
  height: 32px;
  line-height: 32px;
}

.pagination-container :deep(.el-pagination .el-pager li.is-active) {
  background-color: #0071e3;
  color: white;
}

/* 地图对话框样式 */
.full-map-container {
  height: 600px;
  width: 100%;
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
}

:deep(.el-dialog__header) {
  padding: 20px 24px;
  margin: 0;
}

:deep(.el-dialog__body) {
  padding: 0 24px 24px;
}

:deep(.el-dialog__title) {
  font-weight: 600;
  font-size: 18px;
  letter-spacing: -0.01em;
}

:deep(.el-dialog__headerbtn) {
  top: 18px;
  right: 20px;
}

/* 求购信息样式 */
.wanted-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  margin-bottom: 20px;
}

.wanted-card {
  border-radius: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  border: none;
  overflow: hidden;
}

.wanted-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.12);
}

.wanted-content {
  padding: 16px;
}

.wanted-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
}

.wanted-title {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #1d1d1f;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  flex: 1;
}

.wanted-tag {
  background-color: #0071e3;
  color: white;
  font-size: 12px;
  font-weight: 500;
  padding: 2px 8px;
  border-radius: 10px;
  white-space: nowrap;
}

.wanted-description {
  color: #424245;
  font-size: 14px;
  margin: 8px 0 16px;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  line-height: 1.5;
  min-height: 42px;
}

.wanted-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  font-size: 12px;
  color: #86868b;
}

.wanted-user {
  display: flex;
  align-items: center;
  gap: 5px;
}

.wanted-stats {
  display: flex;
  gap: 12px;
}

.wanted-footer {
  display: flex;
  justify-content: flex-end;
}

/* 响应式调整 */
@media (max-width: 900px) {
  .main-content {
    flex-direction: column;
  }
  
  .intro-sidebar {
    width: 100%;
    margin-bottom: 24px;
  }
  
  .action-buttons {
    flex-wrap: wrap;
  }
  
  .controls-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 16px;
  }
  
  .filter-bar {
    width: 100%;
  }
  
  .filter-options {
    width: 100%;
    justify-content: space-between;
  }
}

@media (max-width: 600px) {
  .school-header {
    height: auto;
    padding: 24px 0;
  }
  
  .header-content {
    flex-direction: column;
    gap: 20px;
    padding: 24px;
  }
  
  .school-basic {
    flex-direction: column;
    text-align: center;
  }
  
  .school-title-area {
    margin-left: 0;
    margin-top: 16px;
  }
  
  .school-stats {
    justify-content: center;
  }
  
  .action-buttons {
    width: 100%;
    justify-content: center;
  }
}

.stats-card {
  border-radius: 20px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  border: none;
  overflow: hidden;
  background-color: #fff;
  transition: transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), box-shadow 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.12);
}

.stats-content {
  padding: 16px;
  display: flex;
  justify-content: space-around;
}

.stat-box {
  text-align: center;
  padding: 8px 0;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #0071e3;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 12px;
  color: #86868b;
}

.action-card {
  border-radius: 20px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  border: none;
  overflow: hidden;
  background-color: #fff;
  transition: transform 0.3s cubic-bezier(0.25, 0.1, 0.25, 1), box-shadow 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
  margin-top: 20px;
}

.action-content {
  padding: 8px;
}

.action-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 8px;
}

.action-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 12px;
  border-radius: 12px;
  cursor: pointer;
  transition: all 0.2s ease;
  background-color: #f5f5f7;
}

.action-item:hover {
  background-color: #e5e5ea;
  transform: translateY(-2px);
}

.action-item .el-icon {
  font-size: 24px;
  margin-bottom: 4px;
  color: #0071e3;
}

.action-item span {
  font-size: 13px;
  font-weight: 500;
}

.quick-actions-container {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 260px;
  z-index: 10;
}

.quick-actions-card {
  border-radius: 16px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
  border: none;
  overflow: hidden;
  background-color: rgba(255, 255, 255, 0.92);
  backdrop-filter: blur(10px);
  -webkit-backdrop-filter: blur(10px);
  }
  
.quick-actions-card .card-header {
  padding: 10px 14px 6px;
}

.quick-actions-card .card-header h3 {
  font-size: 16px;
  margin: 0;
}

.quick-actions-card .action-content {
  padding: 6px;
}

.quick-actions-card .action-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 6px;
}

.quick-actions-card .action-item {
  padding: 10px;
}

.quick-actions-card .action-item .el-icon {
  font-size: 22px;
}

.quick-actions-card .action-item span {
  font-size: 12px;
}

@media (max-width: 1100px) {
  .school-header {
    width: 100%;
  }
  
  .quick-actions-container {
    position: static;
    width: 100%;
    margin-bottom: 20px;
  }
}

/* 添加调试信息样式 */
.debug-info {
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  padding: 10px;
  margin-bottom: 15px;
  border-radius: 8px;
  font-family: monospace;
  font-size: 12px;
  white-space: pre-wrap;
  overflow: auto;
  max-height: 200px;
}

.debug-btn {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 5px 10px;
  border-radius: 4px;
  margin-right: 10px;
  margin-top: 5px;
  cursor: pointer;
  }

.debug-btn:hover {
  background-color: #0056b3;
}

.apple-style-dialog {
  border-radius: 20px;
  overflow: hidden;
}

.apple-style-input {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
}

.apple-style-select {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
}

.apple-style-input-number {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
}

.apple-style-textarea {
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
  margin-bottom: 20px;
  width: 100%;
  height: 150px;
}

.apple-style-btn {
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 10px 20px;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.apple-style-btn:hover {
  background-color: #0056b3;
}

.apple-style-btn.cancel-btn {
  background-color: #ccc;
}

.apple-style-btn.cancel-btn:hover {
  background-color: #999;
}

.form-item-tips {
  font-size: 12px;
  color: #86868b;
  padding-top: 2px; /* 原来是4px */
  line-height: 1.2; /* 原来是1.4 */
  margin-bottom: 0;
}

:deep(.apple-style-dialog .el-form-item__content) {
  margin-left: 0 !important;
  flex: 1;
  line-height: 1.2 !important; /* 减少行高 */
}

.location-container {
  display: flex;
  gap: 10px;
}

.map-container {
  flex: 1;
  height: 200px;
  border: 1px solid #ccc;
  border-radius: 10px;
  overflow: hidden;
}

.map-placeholder {
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  color: #888;
}

.apple-style-upload {
  margin-bottom: 20px;
}

.preview-dialog {
  width: 300px;
  height: 400px;
}

.location-input {
  flex: 1;
  border: 1px solid #ccc;
  border-radius: 10px;
  padding: 10px;
}

/* General Dialog Style */
:deep(.apple-style-dialog .el-dialog__header) {
  padding: 20px 24px;
  border-bottom: 1px solid #ebebeb; /* Subtle separator */
  margin-right: 0; 
}

:deep(.apple-style-dialog .el-dialog__title) {
  font-size: 18px; 
  font-weight: 600; 
  color: #333; 
}

:deep(.apple-style-dialog .el-dialog__body) {
  padding: 24px 24px 0px; /* 减少底部内边距 */
}

:deep(.apple-style-dialog .el-dialog__footer) {
  padding: 0 24px 10px; /* 原来是16px */
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  margin-top: 0; /* 去掉顶部边距 */
  padding-top: 0; /* 去掉顶部内边距 */
}

/* Form item enhancements */
.product-form :deep(.el-form-item__label),
.apple-style-dialog :deep(.el-form-item__label) { /* For wanted form items */
  color: #555; 
  font-weight: 500;
  padding-right: 12px; /* Ensure space between label and input */
}

/* Inputs, Selects, Textareas - Unified Apple-like Style */
.apple-style-input :deep(.el-input__wrapper),
.apple-style-select :deep(.el-select__wrapper),
.apple-style-input-number :deep(.el-input__wrapper),
.apple-style-textarea :deep(.el-textarea__inner) {
  background-color: #f9f9f9; /* Light grey background for inputs */
  border: 1px solid #d1d1d1; /* Slightly darker subtle border */
  border-radius: 8px; /* Consistent rounded corners */
  padding: 0 12px; /* Horizontal padding */
  box-shadow: none; /* Remove default shadows if any */
  transition: border-color 0.2s, box-shadow 0.2s;
  font-size: 14px;
  color: #333; /* Input text color */
  height: 40px; /* Consistent height */
  line-height: 38px; /* Vertically center text */
}

.apple-style-select :deep(.el-select__wrapper){
    /* el-select wrapper might need specific height if content varies */
}

.apple-style-input :deep(.el-input__inner),
.apple-style-select :deep(.el-select__placeholder),
.apple-style-select :deep(.el-select__input), /* For select input text */
.apple-style-select :deep(.el-select__selected-item), /* For selected item text */
.apple-style-input-number :deep(.el-input__inner) {
    height: 38px; /* Ensure inner elements also respect height */
    line-height: 38px;
}


.apple-style-input :deep(.el-input__wrapper:hover),
.apple-style-select :deep(.el-select__wrapper:hover),
.apple-style-input-number :deep(.el-input__wrapper:hover),
.apple-style-textarea :deep(.el-textarea__inner:hover) {
  border-color: #b0b0b0; /* Slightly darker border on hover */
}

.apple-style-input :deep(.el-input__wrapper:focus-within),
.apple-style-select :deep(.el-select__wrapper.is-focused),
.apple-style-input-number :deep(.el-input__wrapper:focus-within),
.apple-style-textarea :deep(.el-textarea__inner:focus) {
  border-color: #007aff; /* Apple blue focus highlight */
  box-shadow: 0 0 0 2px rgba(0, 122, 255, 0.2); /* Subtle focus ring */
}

.apple-style-textarea :deep(.el-textarea__inner) {
  padding: 10px 12px; /* Specific padding for textarea */
  min-height: 100px; /* Default min height */
  height: auto; /* Allow textarea to grow */
  line-height: 1.5; /* Better for multi-line text */
}

/* Input Number specific styling */
.apple-style-input-number {
  width: 100%; /* Make input number take full width of its column */
}
.apple-style-input-number :deep(.el-input-number__decrease),
.apple-style-input-number :deep(.el-input-number__increase) {
  background-color: #f0f0f0;
  border: 1px solid #d1d1d1;
  width: 32px; /* Adjust width of controls */
  height: calc(100% - 2px); /* Match wrapper height minus borders */
  top: 1px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.apple-style-input-number :deep(.el-input-number__decrease) {
  border-left: none;
  border-right: 1px solid #d1d1d1;
  border-top-left-radius: 7px;  /* Match wrapper border-radius */
  border-bottom-left-radius: 7px;
}
.apple-style-input-number :deep(.el-input-number__increase) {
  border-right: none;
  border-left: 1px solid #d1d1d1;
  border-top-right-radius: 7px; /* Match wrapper border-radius */
  border-bottom-right-radius: 7px;
}
.apple-style-input-number :deep(.el-input-number__decrease:hover),
.apple-style-input-number :deep(.el-input-number__increase:hover) {
  color: #007aff;
  background-color: #e5e5e5;
}
.apple-style-input-number :deep(.el-input__wrapper) {
  padding-left: 0; /* Controls are outside now */
  padding-right: 0;
}
.apple-style-input-number :deep(.el-input__inner) {
  text-align: center; /* Center align text in input number */
}


/* Buttons - Apple Style */
.dialog-footer .apple-style-btn {
  padding: 10px 24px; /* More prominent buttons */
  border-radius: 8px; /* Consistent rounded corners */
  font-weight: 500;
  font-size: 15px; /* Slightly larger font for buttons */
  border: none;
  transition: background-color 0.2s, transform 0.1s;
  line-height: 1.5; /* Ensure text is well-aligned in button */
}
.dialog-footer .apple-style-btn:active {
    transform: scale(0.98); /* Slight press effect */
}

.dialog-footer .apple-style-btn.confirm-btn {
  background-color: #007aff; /* Apple blue */
  color: white;
}

.dialog-footer .apple-style-btn.confirm-btn:hover {
  background-color: #005ecb; /* Darker blue on hover */
}

.dialog-footer .apple-style-btn.cancel-btn {
  background-color: #e5e5ea; /* Light grey for cancel */
  color: #333;
}

.dialog-footer .apple-style-btn.cancel-btn:hover {
  background-color: #dcdce0; /* Slightly darker grey on hover */
}

/* Form item spacing */
.apple-style-dialog :deep(.el-form-item) {
  margin-bottom: 15px; /* 原来是22px，减少间距 */
}
.apple-style-dialog :deep(.el-form-item .el-form-item__content) {
    line-height: normal; /* Reset line-height if inherited undesirably */
}


/* Location container specific */
.location-container {
  display: flex;
  gap: 16px; /* Increased gap for clarity */
  align-items: stretch; /* Make map and input same height */
}

.map-container {
  flex: 1;
  min-height: 180px; /* Increased height */
  border-radius: 8px; /* Match input rounding */
  border: 1px solid #d1d1d1;
  background-color: #f9f9f9; /* Placeholder background */
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden; /* Ensure map respects border radius */
}
.map-placeholder {
  color: #86868b; /* Apple secondary text color */
  font-size: 14px;
}


.location-input.apple-style-input :deep(.el-input__wrapper) {
  /* Location input should already be styled by .apple-style-input */
}

/* Upload component */
.apple-style-upload :deep(.el-upload--picture-card) {
  background-color: #f9f9f9;
  border: 1px dashed #d1d1d1; /* Standard dash for upload */
  border-radius: 8px;
  width: 104px; 
  height: 104px;
  line-height: 104px; /* Center icon */
  display: flex;
  align-items: center;
  justify-content: center;
  transition: border-color 0.2s;
}
.apple-style-upload :deep(.el-upload--picture-card:hover) {
  border-color: #007aff;
}
.apple-style-upload :deep(.el-upload-list__item) {
  border-radius: 8px;
  width: 104px;
  height: 104px;
  border: 1px solid #d1d1d1;
}
.apple-style-upload :deep(.el-upload-list__item-actions .el-icon),
.apple-style-upload :deep(.el-upload--picture-card .el-icon) {
    font-size: 24px; /* Adjust icon size */
    color: #86868b; /* Use a standard icon color */
}
.apple-style-upload :deep(.el-upload--picture-card .el-icon:hover),
.apple-style-upload :deep(.el-upload-list__item-actions .el-icon:hover) {
    color: #007aff;
}

/* Tips below form items */
.form-item-tips {
  font-size: 12px;
  color: #86868b; /* Apple's secondary text color */
  padding-top: 4px; /* Space from the input */
  line-height: 1.4;
}

/* Preview dialog for uploaded images */
.preview-dialog :deep(.el-dialog__body) {
  padding: 10px; /* Minimal padding for image preview */
  display: flex;
  justify-content: center;
  align-items: center;
}
.preview-dialog :deep(img) {
  max-width: 100%;
  max-height: 80vh;
  border-radius: 8px;
}

/* Remove original basic apple-style placeholders if they were just on the component tag */
.apple-style-input,
.apple-style-select,
.apple-style-input-number,
.apple-style-textarea {
  /* These classes on the component tags themselves might not need styling if :deep is used for children */
  /* For example, if they had 'border: 1px solid #ccc', it's now handled by :deep styles */
  /* We can clear them to avoid conflicts if they were simplistic */
  border: none;
  padding: 0;
  margin-bottom: 0; /* Margin is now on el-form-item */
  background: transparent;
}

/* 现代化输入框样式和动效 */
.modern-input :deep(.el-input__wrapper) {
  background-color: rgba(247, 247, 247, 0.8);
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  box-shadow: none;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
  overflow: hidden;
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
}

.modern-input :deep(.el-input__wrapper:hover) {
  border-color: #c0c0c0;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.modern-input :deep(.el-input__wrapper:focus-within) {
  border-color: #007aff;
  background-color: rgba(255, 255, 255, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 121, 255, 0.12);
}

.modern-input :deep(.el-input__inner) {
  transition: all 0.3s ease;
}

.modern-input :deep(.el-input__wrapper:focus-within .el-input__inner) {
  letter-spacing: 0.01em;
}

/* 应用到所有输入框 */
.apple-style-input :deep(.el-input__wrapper),
.apple-style-select :deep(.el-select__wrapper),
.apple-style-input-number :deep(.el-input__wrapper),
.apple-style-textarea :deep(.el-textarea__inner) {
  background-color: rgba(247, 247, 247, 0.8);
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 0 16px;
  box-shadow: none;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
  font-size: 14px;
  color: #333;
  height: 44px;
  line-height: 44px;
  backdrop-filter: blur(5px);
  -webkit-backdrop-filter: blur(5px);
}

.apple-style-input :deep(.el-input__wrapper:hover),
.apple-style-select :deep(.el-select__wrapper:hover),
.apple-style-input-number :deep(.el-input__wrapper:hover),
.apple-style-textarea :deep(.el-textarea__inner:hover) {
  border-color: #c0c0c0;
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.apple-style-input :deep(.el-input__wrapper:focus-within),
.apple-style-select :deep(.el-select__wrapper.is-focused),
.apple-style-input-number :deep(.el-input__wrapper:focus-within),
.apple-style-textarea :deep(.el-textarea__inner:focus) {
  border-color: #007aff;
  background-color: rgba(255, 255, 255, 0.95);
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 121, 255, 0.12);
}

.apple-style-textarea :deep(.el-textarea__inner) {
  padding: 16px;
  min-height: 120px;
  height: auto;
  line-height: 1.6;
  border-radius: 12px;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
}

.apple-style-textarea :deep(.el-textarea__inner:hover) {
  transform: translateY(-2px);
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
}

.apple-style-textarea :deep(.el-textarea__inner:focus) {
  transform: translateY(-2px);
  box-shadow: 0 8px 20px rgba(0, 121, 255, 0.12);
}

/* 更现代的选择器样式 */
.apple-style-select :deep(.el-select__wrapper) {
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
}

.apple-style-select :deep(.el-select__tags) {
  margin: 4px 0;
}

/* 更现代的按钮样式 */
.dialog-footer .apple-style-btn {
  padding: 12px 28px;
  border-radius: 12px;
  font-weight: 500;
  font-size: 15px;
  border: none;
  transition: all 0.3s cubic-bezier(0.25, 0.8, 0.5, 1);
  line-height: 1.5;
}

.dialog-footer .apple-style-btn:hover {
  transform: translateY(-3px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.dialog-footer .apple-style-btn:active {
  transform: translateY(-1px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.1);
}

.dialog-footer .apple-style-btn.confirm-btn {
  background-color: #007aff;
  color: white;
  box-shadow: 0 4px 12px rgba(0, 121, 255, 0.2);
}

.dialog-footer .apple-style-btn.confirm-btn:hover {
  background-color: #0066dd;
  box-shadow: 0 8px 20px rgba(0, 121, 255, 0.3);
}

.dialog-footer .apple-style-btn.cancel-btn {
  background-color: #f2f2f7;
  color: #333;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
}

.dialog-footer .apple-style-btn.cancel-btn:hover {
  background-color: #e5e5ea;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.08);
}

.location-input-container {
  display: flex;
  flex-direction: column;
  margin-bottom: 0; /* 减少底部间距 */
}

.location-status {
  margin-top: 4px; /* 原来是8px */
  font-size: 12px;
  display: flex;
  align-items: center;
  animation: fadeIn 0.3s ease-in-out;
  overflow: hidden;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-5px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.location-status .el-tag {
  display: inline-flex;
  align-items: center;
  padding: 4px 8px;
  border-radius: 8px;
  font-weight: 500;
  line-height: 1.4;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

.location-status .el-tag--light.el-tag--success {
  background-color: rgba(103, 194, 58, 0.1);
  border-color: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}

.location-status .el-tag--light.el-tag--info {
  background-color: rgba(144, 147, 153, 0.1);
  border-color: rgba(144, 147, 153, 0.2);
  color: #909399;
}

.location-status .el-tag--light.el-tag--warning {
  background-color: rgba(230, 162, 60, 0.1);
  border-color: rgba(230, 162, 60, 0.2);
  color: #e6a23c;
}

.location-status .el-tag--light.el-tag--error {
  background-color: rgba(245, 108, 108, 0.1);
  border-color: rgba(245, 108, 108, 0.2);
  color: #f56c6c;
}

/* 商品发布对话框样式 */
.product-top-section {
  margin-bottom: 10px; /* 原来是20px */
}

.main-image-uploader {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.main-product-image {
  width: 100%;
  height: 220px; /* 原来是280px，减小为220px */
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px dashed #d9d9d9;
  border-radius: 12px;
  overflow: hidden;
  background-color: #fafafa;
  transition: all 0.3s;
}

.main-product-image:hover {
  border-color: #409eff;
  background-color: #f0f9ff;
  box-shadow: 0 0 8px rgba(0, 137, 255, 0.2);
}

.main-image-preview {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

.main-image-placeholder {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  color: #8c939d;
}

.upload-icon {
  font-size: 28px;
  margin-bottom: 8px;
}

.upload-text {
  font-size: 14px;
}

.additional-images {
  margin-top: 0px; /* 原来是18px */
  border-top: 1px dashed #eaeaea;
  padding-top: 0px; /* 原来是18px */
  margin-bottom: 0px; /* 原来是10px */
}

/* 正方形商品描述框样式 */
.square-description {
  height: 100%;
}

.square-textarea :deep(.el-textarea__inner) {
  height: 140px;
  min-height: 140px;
  overflow-y: auto;
  resize: none;
  background-color: rgba(247, 247, 247, 0.6);
  box-shadow: 0 2px 8px rgba(0,0,0,0.04);
  border: 1px solid #e0e0e0;
}

.square-textarea :deep(.el-textarea__inner:hover) {
  border-color: #c0c0c0;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
}

.square-textarea :deep(.el-textarea__inner:focus) {
  border-color: #007aff;
  background-color: rgba(255, 255, 255, 0.95);
  box-shadow: 0 4px 16px rgba(0, 121, 255, 0.12);
}

/* 缩短输入框宽度 */
.apple-style-input, 
.apple-style-select {
  max-width: 50%;
}

/* 缩短第一组输入框的宽度 */
.product-form .product-top-section .el-form-item .el-input,
.product-form .product-top-section .el-form-item .el-select {
  width: 50%;
}

.half-width-input {
  width: 50% !important;
  max-width: 50% !important; 
}

.half-width-input :deep(.el-input__wrapper),
.half-width-input :deep(.el-select__wrapper) {
  width: 100%;
}

/* 表单标签加粗加大并统一放左边 */
.product-form :deep(.el-form-item__label),
.apple-style-dialog :deep(.el-form-item__label) {
  font-weight: bold !important;
  font-size: 16px !important;
  color: #333 !important;
  padding-right: 15px !important;
  text-align: left !important;
  float: left !important;
  line-height: 40px !important;
  margin-right: 10px !important;
}

/* 确保表单项正确对齐 */
.product-form :deep(.el-form-item),
.apple-style-dialog :deep(.el-form-item) {
  display: flex !important;
  flex-direction: row !important;
  align-items: flex-start !important;
  margin-bottom: 15px !important; /* 原来是22px，减少间距 */
}

/* 调整内容区域宽度 */
.product-form :deep(.el-form-item__content),
.apple-style-dialog :deep(.el-form-item__content) {
  margin-left: 0 !important;
  flex: 1;
}

/* 处理必填项星号 */
.product-form :deep(.el-form-item.is-required .el-form-item__label::before),
.apple-style-dialog :deep(.el-form-item.is-required .el-form-item__label::before) {
  color: #f56c6c !important;
  margin-right: 6px !important;
  font-size: 18px !important;
}

/* 修改所有表单项提示内容的间距 */
.product-form :deep(.el-form-item__error),
.apple-style-dialog :deep(.el-form-item__error) {
  padding-top: 2px;
  line-height: 1.2;
}

/* 位置输入框加宽 */
.location-input-container .apple-style-input {
  max-width: 100% !important; /* 覆盖半宽设置 */
  width: 100% !important;
}

/* 位置输入框专用样式 */
.location-field {
  font-size: 15px !important;
}

.location-field :deep(.el-input__wrapper) {
  padding-left: 16px !important;
  padding-right: 16px !important;
}

/* 从 Requests.vue 复制的 ios-request-card 相关样式 */
.ios-request-card {
  background-color: #fff;
  border-radius: 12px; /* 统一圆角风格 */
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06); /* 更精致的阴影 */
  padding: 18px; /* 内边距 */
  transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1); /* 平滑过渡 */
  display: flex;
  flex-direction: column;
  border: 1px solid #f0f0f0; /* 淡化边框 */
  margin-bottom: 16px; /* 与其他卡片保持一致的间距，如果.wanted-grid没有gap的话 */
}

.ios-request-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 8px 18px rgba(0, 0, 0, 0.08); /* 悬浮时阴影加深 */
}

.request-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px; /* 头部与主体间距 */
  padding-bottom: 10px; /* 头部底边距，可选，如果需要分割线 */
  border-bottom: 1px solid #f5f5f5; /* 头部与主体分割线，可选 */
}

.user-info {
  display: flex;
  align-items: center;
}

.user-details {
  margin-left: 10px; /* 用户头像与信息间距 */
  display: flex;
  flex-direction: column;
}

.user-name {
  font-weight: 600; /* 用户名加粗 */
  font-size: 15px; /* 用户名大小 */
  color: #333;
  line-height: 1.3;
}

.user-school {
  font-size: 13px; /* 学校信息字号 */
  color: #777; /* 学校信息颜色 */
  line-height: 1.3;
}

.request-actions-top {
  display: flex;
  align-items: center;
}

.request-time {
  font-size: 12px; /* 时间字号 */
  color: #999; /* 时间颜色 */
  margin-right: 10px; /* 时间与收藏按钮间距 */
}

.favorite-button.el-button {
  padding: 5px; /* 调整按钮内边距让图标居中且不占太大空间 */
  min-height: auto; /* 重置Element Plus按钮的最小高度 */
  border: none !important; /* 移除边框 */
  background: transparent !important; /* 透明背景 */
}

.favorite-button .el-icon {
  font-size: 18px; /* 收藏图标大小 */
  color: #ccc; /* 默认图标颜色 */
}

.favorite-button.is-favorite .el-icon {
  color: #E6A23C; /* 收藏状态颜色 (Element Plus warning color) */
}

.request-body {
  margin-bottom: 12px; /* 主体与底部间距 */
  flex-grow: 1; /* 占据剩余空间 */
}

.request-title {
  font-size: 17px; /* 标题字号 */
  font-weight: 600; /* 标题加粗 */
  color: #222; /* 标题颜色 */
  margin: 0 0 8px 0; /* 标题与其他内容间距 */
  line-height: 1.4;
  /* 多行文字溢出显示省略号 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2; /* 显示两行 */
  -webkit-box-orient: vertical;
}

.request-content {
  font-size: 14px; /* 内容字号 */
  color: #555; /* 内容颜色 */
  line-height: 1.6;
  margin-bottom: 10px; /* 内容与标签间距 */
  /* 多行文字溢出显示省略号 */
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 显示三行 */
  -webkit-box-orient: vertical;
}

.request-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 6px; /* 标签间距 */
  margin-bottom: 10px; /* 标签与底部间距，如果下方还有内容 */
}

.request-tags .el-tag {
  font-size: 12px; /* 标签字号 */
  height: 24px; /* 标签高度 */
  line-height: 22px; /* 标签内文字行高 */
  padding: 0 8px; /* 标签内边距 */
}

.request-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px; /* 底部上边距，可选，如果需要分割线 */
  border-top: 1px solid #f5f5f5; /* 底部与主体分割线，可选 */
}

.request-budget {
  font-size: 16px; /* 预算字号 */
  font-weight: bold; /* 预算加粗 */
  color: #F56C6C; /* 预算颜色 (Element Plus danger color) */
}

.request-actions .el-button {
  font-size: 13px; /* 底部按钮字号 */
  padding: 6px 12px; /* 底部按钮内边距 */
}

/* 确保 wanted-grid 使用 grid 布局 */
.wanted-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); /* 与Requests.vue中的ios-requests-grid保持一致或按需调整 */
  gap: 20px;
}

/* 移除原 wanted-card 和子元素的部分样式，因为现在使用 ios-request-card */
/* .wanted-card { ... } */
/* .wanted-card-content { ... } */
/* .wanted-image-placeholder { ... } */
/* .wanted-image { ... } */
/* .wanted-info { ... } */
/* .wanted-title { ... } /* .request-title 将替代它 */
/* .wanted-description { ... } /* .request-content 将替代它 */
/* .wanted-meta { ... } */
/* .wanted-user { ... } */
/* .wanted-price { ... } */
/* .wanted-card-footer { ... } /* .request-footer 将替代它 */

</style> 